how to set element attribute with javascript in IE6..? It seems setAttribute doesn’t work. I really need to do it on the fly. Thanks.
Code
<script type="text/javascript" language="javascript">
menuItems = document.getElementById("menu").childNodes;
for (i = 0; i < menuItems.length; i++)
{
if (menuItems[i].className != "blue")
menuItems[i].setAttribute('onmouseover', 'HoverMenu(this)');
}
</script>
(Most of the below was before the OP clarified they were setting an event handler; left the list of other issues in case others find them useful)
IE6 makes a mess of several aspects of
setAttribute. Without knowing the exact problem you were dealing with (this was before the edit inidicating it was an event handler), it’s hard to be sure whether that’s really the problem, but here are a couple of known issues:You can’t use
setAttributeto set event handlersIt’s best to set event handlers using the reflected property or with
addEventListener[standard] /attachEvent[IE], notsetAttribute(and you can’t usesetAttributeon IE).So, any of these will work:
…not
The
addEventListener/attachEventway of doing this is cool for other reasons: You can have multiple event listeners on the same event of an element. You can’t do that using the reflected property.So for your specific situation:
Certain attributes need their modified names
classThe correct way to set the class attribute is to use the reflected property
className:or on modern browsers (so, not IE6!) you can use
classList.One of IE6’s many
setAttributebugs is that this doesn’t work:Instead, IE6 (and probably a couple of other versions) make you use
"className"instead of"class", even though that makes no sense whatsoever. The reflected property has the nameclassNamebecause it used to be that in JavaScript, you couldn’t use reserved words (likeclassorfororif) as property literals (obj.classwas invalid). That’s not been true for a while now (ECMAScript 5 fixed it), but that’s why the reflected property isclassName, notclass.But since
setAttributetakes a string, it should accept the proper name of the attribute. The fact it doesn’t is just an IE bug (and one they’ve fixed in modern versions of IE if they’re not in [in]compatibility mode).forSimilarly, to set the
forattribute (for instance, onlabels), one uses thehtmlForreflected property:On any non-broken browser, you can also use
setAttribute:…but not on IE6, it wants
"htmlFor"instead of"for"for the same reason it wants"className"rather than"class"(e.g, because it’s broken).This page has quite a list of attributes that are problematic with IE.
setAttributecan’t be used to set thestyleattribute…you have to use the
styleproperty instead; but to be fair, that’s usually a more convenient way. Example: This won’t work on IE:…but this will:
Slightly OT: Look at libraries
JavaScript libraries like Prototype, jQuery, Closure, or any of several others will make most of the above a lot easier and smooth out differences amongst browsers if you go through their APIs.