Home >Web Front-end >JS Tutorial >A brief explanation of the sub-element filter selector in jQuery_jquery

A brief explanation of the sub-element filter selector in jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 15:04:502041browse

The filtering rule of the child element filter is to obtain the corresponding element through the relationship between the parent element and the child element.

2016418172315508.png (694×613)

$('li:first-child').css('background', '#ccc'); //每个父元素第一个li 元素 
 
$('li:last-child').css('background', '#ccc'); //每个父元素最后一个li 元素 
 
$('li:only-child').css('background', '#ccc'); //每个父元素只有一个li 元素 
 
$('li:nth-child(odd)').css('background', '#ccc'); //每个父元素奇数li 元素 
 
$('li:nth-child(even)').css('background', '#ccc'); //每个父元素偶数li 元素 
 
$('li:nth-child(2)').css('background', '#ccc'); //每个父元素第三个li 元素 

We know how to use

:first

The filter selector can obtain the first child element in the specified parent element, but this selector returns only one element, not a collection, and use

:first-child

The child element filter selector can obtain the first child element returned in each parent element. It is a collection and is commonly used for selection processing of multiple collection data.

As shown below, if you want to get the first li in each ul on the page and change its color. Then you can use

: first-child

<body>
  <h3>该百年额米格“蔬菜水果”中第一行的文字颜色</h3>
  <ul>
    <li>芹菜</li>
    <li>茄子</li>
    <li>萝卜</li>
    <li>大白菜</li>
    <li>西红柿</li>
  </ul>
  <ul>
    <li>橘子</li>
    <li>香蕉</li>
    <li>葡萄</li>
    <li>苹果</li>
    <li>西瓜</li>
  </ul>
</body>
<script type="text/javascript">
  $("li:first-child").css("color", "red");
</script>

The effect displayed in the browser:

2016418172340814.jpg (489×326)

Passed

$("li:first-child")
The

selector code obtains the first 25edfb22a4f469ecb59f1190150159c6 element of the two ff6d136ddc5fdfeffaf53ff6ee95f185 parent elements and uses

css()
The

method modifies the text color they display on the page.

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