user1940321
user1940321

Reputation:

How to select all <li> in an <ul> with a classname "nav"?

Having a real hard time with this since I'm new to jQuery, but I'm not sure whether the tutorial I'm working on is broken or if it's me but I'm using the following code to select all li in an ul with a class of nav.

$(".nav ul li");

Is this correct? Could someone point me in the right direction?

Upvotes: 21

Views: 74000

Answers (6)

murphy1312
murphy1312

Reputation: 563

$('ul.nav li')

As suggested selects ALL the <li /> in <ul class="nav" />. If you only want the immediate children use:

$('ul.nav > li')

https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator

Upvotes: 0

Bryan Myers
Bryan Myers

Reputation: 559

Here's a tip that will help people learn selectors:

Use the Chrome browser Open up any page Right click on the page and select "Inspect element" In the element inspector select the Console tab

You can type commands right into this console. Try a few selectors only and see what you get. If you type $('p') and hit enter it will list out all the p elements. If you enter $('ul.nav li) it will show you if that selector works (returns anything). If the command does not result in a valid selector it will return [].

Upvotes: 13

Alexander
Alexander

Reputation: 23537

Constructively,

  1. All ul elements:

    $("ul")
    
  2. All ul elements with a classname nav:

    $("ul.nav")
    
  3. All li elements under all ul elements with a classname nav:

    $("ul.nav li")
    

Upvotes: 47

hyankov
hyankov

Reputation: 4130

All li in an ul with a class of nav:

$("ul.nav li");

Upvotes: 2

adeneo
adeneo

Reputation: 318302

select all li in an ul with a class of nav

like so, selects all li's in an ul with the .nav class:

$('ul.nav li')

Upvotes: 2

nbrooks
nbrooks

Reputation: 18233

Append it after the element selector:

$("ul.nav li");

This selects all <li> elements in a <ul class="nav"> element

See the docs: http://api.jquery.com/class-selector/

Upvotes: 2

Related Questions