Reputation: 12695
I have a hierarchical UL list. How to - using jQuery - get the all parents of the selected LI element and change the <a>
's background color inside each parent ?
<ul id="nav">
<li>
<a href="#">A</a>
<ul>
<li>
<a href="#">B</a>
<ul>
<li><a href="#">B1</a></li>
<li><a href="#">B2</a></li>
<li><a href="#">B3</a></li>
<li><a href="#">B4</a></li>
<li><a href="#">B5</a></li>
</ul>
</li>
<li>
<a href="#">C</a>
<ul>
<li><a href="#">C1</a></li>
<li><a href="#">C2</a></li>
<li><a href="#">C3</a></li>
</ul>
</li>
</ul>
If I e.g. select <a href="#">B4</a>
, <a href="#">B</a>
and <a href="#">A</a>
will be also selected
Upvotes: 0
Views: 3116
Reputation: 348972
The following will bind a click
event to all <li>
elements, and literally apply a background color to all parents and itself.
$('li').click(function() {
$(this).parents().andSelf().css('background-color', 'red');
});
jQuery docs:
Upvotes: 6
Reputation: 2005
Assuming both A and B are UL
elements, the following code should work:
$(this).parents('ul').addClass('new_class');
Upvotes: 1