简体   繁体   中英

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?

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") 

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 [].

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/

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')

所有带有导航类的ul中的li:

$("ul.nav li");
$('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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM