theHack
theHack

Reputation: 2014

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?...

Upvotes: 0

Views: 1060

Answers (2)

Quentin
Quentin

Reputation: 943217

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.

Upvotes: 1

Dr.Molle
Dr.Molle

Reputation: 117314

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.

Upvotes: 2

Related Questions