PANVEGA’s Blog

DotNet Development, SharePoint Customizing, Silverlight, MS Infrastructure and other tips and tricks

Javascript set the setAttibute dynamically for SharePoint Sites

Posted by PANVEGA on January 9, 2009

I have been trying to dynamically set an attribute using setAttribute() in a javaScript mehtod.

I wanna use this way to show the user which link is an external link on the Website. More detailed information in  one of my other posts.

https://panvega.wordpress.com/2008/10/12/open-link-in-a-new-window

Using setAttribute, you should be able to set any attribute on an element. It appears that in IE, trying to set the style attribute does not work.

Problem: Using firefox‘s DOM Browser, i can see that the class attribute is being assigned a class called “NewLinkClass” but the styles associated with this class (just a bold and color) do not show in IE. The styled class does show in Mozilla.

One important exception is class; in Mozilla you can do this (as you would expect) :

if(checkBrowserName(‘MSIE’)){
thisLink.setAttribute(“className“,”NewLinkClass”);
}
else{
//all other browsers
thisLink.setAttribute(“class“,”NewLinkClass”);
}

function checkBrowserName(name){
var agent = navigator.userAgent.toLowerCase();
if (agent.indexOf(name.toLowerCase())>-1) {
return true;
}
return false;
}

Now, I found a better solution with the same result:

thisLink.setAttribute((document.all ? “className” : “class”), “NewLinkClass”);

In the code above, i am using a javascript function to insert a class attribute into the dom. This part works. I then tried to give the div a classname using newdiv.setattribute(“classname”,”NewLinkClass”). For IE I use className and for the rest of the Browsers just class.

Instead of browser sniffing and doing an if/else, you can just to call both statements, since it does no harm (IE ignores the “class” setting, and Mozilla will have both a “class” and “classname” attribute defined).
Good Luck!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: