views:

445

answers:

3
+1  Q: 

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>
    ...
</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?

A: 
$('#navlinks li.selected')

will give you the li with the "selected" class

Rick Hochstetler
+7  A: 

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.

Paolo Bergantino
A: 

For the specific HTML example given, I would prefer:

function changeNavLink(selectedId) {
    $('#' + selectedId).addClass('selected')
                       .siblings('li')
                       .removeClass('selected');
}
Elliot Nelson