Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 237
core Avatar asked Apr 09 '09 21:04

core


People also ask

What are the jQuery selectors?

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.

What are the four types of 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)

How many standard jQuery selectors are there?

Projects In JavaScript & JQuery This tutorial will explain jQuery Selectors with simple examples covering all the three standard selectors.


3 Answers

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.

like image 129
Paolo Bergantino Avatar answered Nov 15 '22 07:11

Paolo Bergantino


$('#navlinks li.selected')

will give you the li with the "selected" class

like image 25
Rick Hochstetler Avatar answered Nov 15 '22 07:11

Rick Hochstetler


For the specific HTML example given, I would prefer:

function changeNavLink(selectedId) {
    $('#' + selectedId).addClass('selected')
                       .siblings('li')
                       .removeClass('selected');
}
like image 34
Elliot Nelson Avatar answered Nov 15 '22 08:11

Elliot Nelson