How to select all <li> in an <ul> with a classname "nav"?
Solution 1
Constructively,
All
ul
elements:$("ul")
All
ul
elements with a classnamenav
:$("ul.nav")
All
li
elements under allul
elements with a classnamenav
:$("ul.nav li")
Solution 2
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 [].
Solution 3
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')
Solution 4
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/
Solution 5
All li in an ul with a class of nav:
$("ul.nav li");
Admin
Updated on May 10, 2020Comments
-
Admin about 4 years
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?
-
Admin over 11 yearsawesome! Thanks! $("ul.nav li") worked just fine. Still trying to wrap my head around this and why that works. :)
-
elclanrs over 11 years@KenBarlo: You can learn how it works by learning css, more info here css.maxdesign.com.au/selectutorial