Need to set the class of a parent div to that of a contained li element
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 w开发者_如何学Pythonhich 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!
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');
it should be :
$('#leftmenu ul li').attr('class');
精彩评论