简体   繁体   中英

set HTML Attribute using 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?...

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.

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.

In this case, 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;
}

Also, don't use for in to walk arrays and array-like objects. for in walks all the properties of an object, not just numbered ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM