tags:

views:

22

answers:

2

I'm working on a side navigation element which needs to change color based on which menu is selected. I'm trying to set the class of a parent div to match that of a li which is part of the menu. Here's the code:

<div class="cols" id="leftMenuWrapper">
    <div id="leftmenu">
        <ul id="navsub_657930_721861">
            <li class="lmenu_item2"><a href="#">Benefits</a></li>
        </ul>
    </div>
</div>

In this example, I need to set the class of "leftmenu" to "lmenu_item2". I tried this jQuery but it didn't work.

$('#leftmenu').addClass($('#leftmenu ul li').class());

I'm assuming the issue is with .class in the code above. Not sure how to grab the class from the li.

Thanks in advance for any help!

+1  A: 

You would use .attr() to get the value of the attribute you want:

$('#leftmenu ul li').attr('className');

Or if this is part of a click handler on the <li> element, you can reference the one that was clicked with this.

$(this).attr('className');
patrick dw
What's the advantage to `className` versus just `class`?
mway
@mway - None, except that it keeps me in the habit of not using the future reserved word `class`, which will break in some situations for some browsers (variable name, property name, etc.). It doesn't break anything as a string, so `"class"` would work just fine here as well.
patrick dw
Ah, touche. I can agree with that.
mway
@mvan - A good example is when creating an element, you can pass an object to set its attributes, like `$('<div>', {class:"myClass"} )`. This will break (in some browsers) if you don't use `className`, or put quotes around `"class"`.
patrick dw
Worked perfect! Thanks.
mmsa
@mmsa - You're welcome. :o)
patrick dw
A: 

it should be :

$('#leftmenu ul li').attr('class');
feridcelik