Reputation: 33059
I'm finding it difficult to find examples of using jQuery, so my bad for asking such a simple question. I've got this ul:
<ul id="navLinks">
<li class="selected" id="homeNavLink"></li>
<li id="aboutNavLink"></li>
<li id="contactNavLink"></li>
...
</ul>
I'd like to write a function to change which li has the "selected" class. Here's my attempt:
function changeNavLink(selectedId) {
$("#navLinks li").each(function() {
$(this).removeClass("selected");
});
$("#" + selectedId).addClass("selected");
}
What am I doing wrong?
Upvotes: 5
Views: 3969
Reputation: 2242
Why dont work with jQuery(this) ? It easier, then call function with params. HTML:
<ul id="navLinks">
<li class="selected" id="homeNavLink"></li>
<li id="aboutNavLink"></li>
<li id="contactNavLink"></li>
</ul>
JS:
$(document).ready(funciton(){
$('#navLinkgs').on('click', 'li', function(){
$this = $(this);
$('#navLinkgs li.selected').removeClass('selected');
$this.addClass('selected');
});
});
Upvotes: 0
Reputation: 11557
For the specific HTML example given, I would prefer:
function changeNavLink(selectedId) {
$('#' + selectedId).addClass('selected')
.siblings('li')
.removeClass('selected');
}
Upvotes: 1
Reputation: 488374
You don't have to do .each
- functions like removeClass
can work on a set of elements just fine.
function changeNavLink(selectedId) {
$("#navLinks li").removeClass('selected')
.filter('#' + selectedId)
.addClass('selected');
}
Should work. What it is doing is selecting all the li
elements, removing the class selected
from all of them, filtering them out to just the one with the ID passed, and adding the class selected
to that one.
Here is a working link showing the code above at work.
Upvotes: 8
Reputation: 3123
$('#navlinks li.selected')
will give you the li with the "selected" class
Upvotes: 1