core core - 10 months ago 26
Javascript Question

jQuery Selectors

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>

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() {
$("#" + selectedId).addClass("selected");

What am I doing wrong?


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)

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.