简体   繁体   中英

Using JQuery select child element of the given parent element

In a panelbar there are many list items <li> (let's say parent items). Every list item has different number of list items (child items).

$(".childItem:nth-child("1");  

This method will select all the first child items of all the parent items. How can I select with jQuery the child item of the parent item I need?

You can use .childItem:nth-of-type(x), where x are the child you want select. MDN

While I will show a JQuery solution, this is such a simple thing that JQuery really is overkill.

 $("ul.list:first-of-type > li:first-of-type").addClass("active");
 .active { background-color: yellow; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="list"> <li>item</li> <li>item</li> <li>item</li> <li>item</li> </ul> <ul class="list"> <li>item</li> <li>item</li> <li>item</li> <li>item</li> </ul> <ul class="list"> <li>item</li> <li>item</li> <li>item</li> <li>item</li> </ul> <ul class="list"> <li>item</li> <li>item</li> <li>item</li> <li>item</li> </ul>

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