The “IE7 setAttribute class” problem!

Martin ZellerJavascript Leave a Comment

This does not work with IE7:
[js]elem.setAttribute(‘class’,  cssClass);[/js] Use this instead:
[js]elem.setAttribute((document.all ? ‘className’ : ‘class’), cssClass);[/js] Problem: document.all exists in IE8 too, but IE8 does not work with ‘className’!
My solution in one of my projects was prototype:
[js]Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;

function SetCssClass(id, cssClass) {
if (Prototype.Browser.IE6 || Prototype.Browser.IE7)
$(id).setAttribute((document.all ? ‘className’ : ‘class’), cssClass);
else $(id).setAttribute(‘class’, cssClass);
}[/js] PS: in IE7 you can set styles to an element this way:
[js]elem.style.setAttribute(‘cssText’, ‘border:1px solid red;’,0);[/js]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.