Friday, February 1, 2008

[Javascript] Change HTML "class" and "style" attributes

It seems trivial, and it is, but if you are going to write a cross browser script, you can find that sometimes (i.e. always) most used browsers, Firefox and Internet Explorer, work in different ways...damn it!
One of those troubles is the class attribute of a generic HTML; I found that in IE you cannot simply set a class attribute to your own HTML node, but you have to set a className node with the list of your CSS classes.
This is THE code:

/* find out which is the browser */
var isIE = (window.ActiveXObject)?true:false;
var isMozilla = (document.implementation.createDocument)?true:false;

/* the name of the attribute, depending on the browser */
var attributeClass = (isIE)?"className":"class";

/* set the attribute */
htmlNode.setAttribute(attributeClass,"classX dummyClass");

Moreover there is also another strange behavious as for the style attribute; if you want to set the whole CSS text of a node's style (and not a particular sub attribute), this is the syntax:

[UPDATE 01 feb. 2008 - 17:50]
Max and other users made me notice that "else if(isMozilla)" may exclude other
kind of browser, not allowing a wide "cross browsering". Thanx guys!

var styleString ="font-size:10px;";

if(isIE) ;
else //if(isMozilla)

I assure you: writing cross browser script is a really butchery task! Try if you don't believe me!


Max said...

These 2 bugs and many more in IE are discussed (with workarounds) over on Web Bug Track.

Bug 242:

If you can not list 6 IE JavaScript bugs off the top of your head, then you need to take a peek. Its unbelievable how many nasty bugs there are.

Johnny Idol said...

Nice blog you got there.

Thanks for pointing out.


Max said...

Actually, I want to comment on your source code.

This isn't the best approach. You are excluding all other standards compliant browsers!

try this instead.

var isIE = (window.ActiveXObject)?true:false;
//no need to define Mozilla

} else { = styleString;

//you don't want "else if()" because you'll exclude Safari, Opera, Konqueror and all other browsers.

Scuffia said...

Max you are right!
I copied & pasted the code from an old script I wrote; actually it was used to test IE and Firefox only, supposing no other browser could be used, as my company installed all the software (including browser).
Anyway you are right :)
Moreover I suppose that with Opera, Safari and etc. the isMozilla flag would be selected to TRUE. Do you think so?
Anyway thanx for your comment!

skor said...

thanks people this helps a lot