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
Release: 2016-05-16 15:04:50
Original
2044 people have browsed it

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 元素 
Copy after login

We know how to use

:first
Copy after login

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
Copy after login

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

Copy after login
<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>
Copy after login
<script type="text/javascript">
  $("li:first-child").css("color", "red");
</script>

Copy after login

The effect displayed in the browser:

2016418172340814.jpg (489×326)

Passed

$("li:first-child")
Copy after login
The

selector code obtains the first

  • element of the two
      parent elements and uses

      css()
      
      Copy after login
      The

      method modifies the text color they display on the page.

  • source:php.cn
    Statement of this Website
    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
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template