开发者

set HTML Attribute using JavaScript

开发者 https://www.devze.com 2023-02-03 10:59 出处:网络
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</sp

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..开发者_如何学JAVA. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消