简体   繁体   中英

jquery - select li inside a ul that is inside ul

I have this:

    <ul>
        <li>
            <ul>
                <li><a>Hello world</a></li>
                <li><a>hi</a></li>
            </ul>
       </li>
       <li><a>hi</a></li>
   </ul>

And i need to select a li that is in the second ul (the one that has the words 'Hello world', for example.)

How do i do that with jQuery?

I tried this:

$('ul li:eq(1) li:eq(1)').doSomthing();

It's fairly straightforward:

ul ul li

This doesn't check for immediate nesting though; the second ul in the selector could very well be more deeply nested. You can restrict this by using > :

ul > li > ul > li

To grab only the first li , it might look something like this:

​$("ul > li > ul > li:first").css("background", "red");​​​​​​​​​​

The approach you attempted, using the :eq pseudo-selector, would have looked more like this:

​$("li:eq(0) li:eq(0)").css("background", "red");​​​​​​​​​​

Remember that index is zero-based, so the first item is always index 0.

savest是使用直接子选择器>

$("ul > li > ul")
try this it will work as you wish

$('ul li> ul li:eq(0)')。css('border','1px solid red');

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