Home > Article > Web Front-end > A brief explanation of the sub-element filter selector in jQuery_jquery
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.
$('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:
Passed
$("li:first-child")
selector code obtains the first 25edfb22a4f469ecb59f1190150159c6 element of the two ff6d136ddc5fdfeffaf53ff6ee95f185 parent elements and uses
css()
method modifies the text color they display on the page.