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?
From stackoverflow
-
$('#navlinks li.selected')will give you the li with the "selected" class
-
You don't have to do
.each- functions likeremoveClasscan 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
lielements, removing the classselectedfrom all of them, filtering them out to just the one with the ID passed, and adding the classselectedto that one.Here is a working link showing the code above at work.
-
For the specific HTML example given, I would prefer:
function changeNavLink(selectedId) { $('#' + selectedId).addClass('selected') .siblings('li') .removeClass('selected'); }
0 comments:
Post a Comment