Home >Web Front-end >JS Tutorial >A brief discussion on the difference between jquery selector :first and :first-child

A brief discussion on the difference between jquery selector :first and :first-child

高洛峰
高洛峰Original
2016-12-06 13:40:091223browse

An example:

<ul>
 <li>John</li>
 <li>Karl</li>
 <li>Brandon</li>
</ul>
<ul>
 <li>Glen</li>
 <li>Tane</li>
 <li>Ralph</li>
</ul>

first means the first one (after merging all parent elements); first-child means the first one (of each parent element)

$('ul li:first') Return to the li where john is located. Find the first li element under all ul

$("ul li:first-child") returns john glen. Find the first element under each ul which is the li element and the dom element.

Extended usage: $("body *:first") represents the first child element under body; $("body *:first-child") represents every element under body that is the first child element

Also, the css selector goes from right to left, if so;

<ul>
 <li>John</li>
 <li>Karl</li>
 <li>Brandon</li>
</ul>
<ul>
 
<div>DIV</div>
 <li>Glen</li>
 <li>Tane</li>
 <li>Ralph</li>
</ul>

Then $("ul li:first-child") only returns John. Find the first child element of each, if The li element matches, otherwise it does not match.

$('li:first') matches the first li element $("li:first-child") matches the first li element, which is the first of a certain element child elements


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn