Reputation:
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
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
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
Reputation: 23537
Constructively,
All ul
elements:
$("ul")
All ul
elements with a classname nav
:
$("ul.nav")
All li
elements under all ul
elements with a classname nav
:
$("ul.nav li")
Upvotes: 47
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
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