I need to select the first lis of each ul in this structure:
<div>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</div>
I have this selector: container.find('div > ul > li:first')
but jquery engine parese first div > ul > li
and then takes the forst result according to :first
. But I want the first li of each ul, something like: div > ul > (li:first)
.
How can I solve this?
You want the :first-child
selector:
Description: Selects all elements that are the first child of their parent.
While :first matches only a single element, the :first-child selector can match more than one: one for each parent. This is equivalent to :nth-child(1).
ref: http://api.jquery.com/first-child-selector/
Example:
container.find('div ul > li:first-child');
Or if you have multiple levels of ul
containing li
's:
container.find('div > ul > li:first-child');
You're looking for jQuery's each() function:
$("#yourdiv ul").each(function(){
$(this).find("li:first");
});
Use "first-child" selector on li element
$("ul li:first-child")
$("#mydiv ul").each(function(){
$('li:eq(0)',this);
});
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.