So this is what my DOM tree looks like:
<div id="content">
<div id="sidebar">
<ul>
<li class="selected"><a href="#">Header 1</a>
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
<li><a href="#">Link 4</a></li>
</ul>
</li>
<li><a href="#">Header 2</a>
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
</ul>
</li>
<li><a href="#">Header 3</a>
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
</ul>
</li>
<li><a href="#">Header 7</a>
<ul>
</ul>
</li>
<li><a href="#">Header 4</a>
<ul>
</ul>
</li>
<li><a href="#">Header 5</a>
<ul>
<li><a href="#">Link 1</a></li>
</ul>
</li>
</ul>
</div>
</div>
So when I want to do a simple addClass and removeClass for one element, this works:
$(document).ready(function() {
$('div#content div#sidebar ul li a').click(function(e) {
if ($(this).parent().hasClass('selected')) {
$(this).parent().removeClass('selected');
}
else {
$(this).parent().addClass('selected');
}
e.preventDefault();
});
});
However, this doesn’t remove the class selected from every ‘peer’ of $(this).parent(). It only removes the class from the parent of the currently selected item.
What I want to do is, when you click on the link Header 2, it adds the class selected to Header 2, and checks all the sibling elements (in this case, lis for the links Header 1 - 7) and removes that class on any siblings if it finds it. So, in effect, there can be only one selected at that level in the DOM tree.
How do I do that?
This selects the
<a>elements nested within the first tier of<li>elements and adds the.selectedclass to its parent<li>element (while also removing all other instances of the.selectedclass).Here is a jsfiddle: http://jsfiddle.net/jasper/RRk25/
This could be optimized:
This saves looking up DOM nodes on every click as they are cached from the time the
document.readyevent fires.Here’s a jsfiddle of the optimization: http://jsfiddle.net/jasper/RRk25/1/