establecer atributo HTML usando JavaScript

I have a navigation bar below

<div id="cmenu" class="cmenu r">

<div id="help"><a onClick="topMenu('help','current')" href="javascript:void(0)"><span>Help</span></a></div>
<div id="refer"><a onClick="topMenu('refer','current')" href="javascript:void(0)"><span>Refer Friends</span></a></div>
<div id="home"><a onClick="topMenu('home','current')" href="javascript:void(0)"><span>Home</span></a></div>

</div>

I'd like to set "class" attribute to "current" in div element when the link is clicked. so, I can specify a new style on the div/link.here is my function:

function topMenu(id,prNode){
var topMenu=document.getElementById("cmenu").getElementsByTagName("div");
for (var a in topMenu){topMenu[a].removeAttribute("class");} //remove all "current" class (third line)
document.getElementById(id).setAttribute("class",prNode);} //set the new div class as "current" (last line)

but, unfortunately. the last line of my function doesn't work... then I try to change the last line to

alert("alert message");

it also doesn't work... but, when I commented the third line of my function, the last line is working.... is there any error syntax on the 3rd line?...

preguntado el 09 de enero de 11 a las 06:01

is using a javascipt library like jquery an option? -

No use un for - in loop to iterate through a nodeList. Ver: developer.mozilla.org/En/DOM/NodeList -

2 Respuestas

setAttribute is horribly broken in older versions of Internet Explorer, don't use it. Assign values to (and read from instead of using getAttribute) the DOM properties that map to attributes instead.

En este caso, className:

function topMenu(id,prNode){
    var topMenu = document.getElementById("cmenu").getElementsByTagName("div");
    for (var i = 0; i < topMenu.length; i++) {
        topMenu[i].className = '';
    }
    document.getElementById(id).className = prNode;
}

Además, no use for in to walk arrays and array-like objects. for in camina todas the properties of an object, not just numbered ones.

Respondido el 09 de enero de 11 a las 13:01

walk the nodeList like an array(not like an object)

for (var a=0;a<topmenu.length;++a){topMenu[a].removeAttribute("class");}

If you walk it like an object, you'll also get the property "length" of the nodeList, what results in an error.

Respondido el 09 de enero de 11 a las 09:01

There is still the problem of IE's broken setAttribute() implementación. - Tim Down

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.