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?
jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
Simple selectors (select elements based on name, id, class) Combinator selectors (select elements based on a specific relationship between them) Pseudo-class selectors (select elements based on a certain state) Pseudo-elements selectors (select and style a part of an element)
Projects In JavaScript & JQuery This tutorial will explain jQuery Selectors with simple examples covering all the three standard selectors.
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.
$('#navlinks li.selected')
will give you the li with the "selected" class
For the specific HTML example given, I would prefer:
function changeNavLink(selectedId) {
$('#' + selectedId).addClass('selected')
.siblings('li')
.removeClass('selected');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With