Home  >  Article  >  Web Front-end  >  Detailed explanation of jQuery child element selector

Detailed explanation of jQuery child element selector

小云云
小云云Original
2018-02-09 14:08:052045browse

This article mainly introduces the child element selector of jQuery selector to you in detail. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.


<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
  <title></title>
  <link rel="stylesheet" href="imooc.css" rel="external nofollow" type="text/css">
  <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>

<body>
  <h2>子元素筛选选择器</h2>
  <h3>:first-child、:last-child、:only-child</h3>
  <p class="left first-p">
    <p class="p">
      <a>:first-child</a>
      <a>第二个元素</a>
      <a>:last-child</a>
    </p>
    <p class="p">
      <a>:first-child</a>
    </p>
    <p class="p">
      <a>:first-child</a>
      <a>第二个元素</a>
      <a>:last-child</a>
    </p>
  </p>

  <script type="text/javascript">
    //查找class="first-p"下的第一个a元素
    //针对所有父级下的第一个
    $(".first-p a:first-child").css("color", "#CD00CD");
  </script>

  <script type="text/javascript">
    //查找class="first-p"下的最后一个a元素
    //针对所有父级下的最后一个
    //如果只有一个元素的话,last也是第一个元素
    $(".first-p a:last-child").css("color", "red");
  </script>

  <script type="text/javascript">
    //查找class="first-p"下的只有一个子元素的a元素
    $(".first-p a:only-child").css("color", "blue");
  </script>


  <h3>:nth-child、:nth-last-child</h3>
  <p class="left last-p">
    <p class="p">
      <a>:first-child</a>
      <a>第二个元素</a>
      <a>第三个元素</a>
      <a>:last-child</a>
    </p>
    <p class="p">
      <a>:first-child</a>
      <a>第二个元素</a>
    </p>
    <p class="p">
      <a>:first-child</a>
      <a>第二个元素</a>
      <a>第三个元素</a>
      <a>:last-child</a>
    </p>
  </p>

  <script type="text/javascript">
    //查找class="last-p"下的第二个a元素
    $(".last-p a:nth-child(2)").css("color", "#CD00CD");
  </script>

  <script type="text/javascript">
    //查找class="last-p"下的倒数第二个a元素
    $(".last-p a:nth-last-child(2)").css("color", "red");
  </script>

</body>

</html>

Related recommendations:

Detailed introduction to the usage of CSS sub-element selector

The above is the detailed content of Detailed explanation of jQuery child element selector. For more information, please follow other related articles on the PHP Chinese website!

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