jQuery children() 方法



jQuery 中的 children() 方法用於選擇所選元素的所有直接子元素。它向下遍歷 DOM 樹以查詢作為所選元素的直接後代的子元素。它不會遍歷所有後代,僅遍歷直接子元素。

注意:如果我們想要深入遍歷並返回孫子或其他後代,我們需要使用 find() 方法。

語法

以下是 jQuery 中 children() 方法的語法:

$(selector).children(filter)

引數

此方法接受以下可選引數:

  • filter: 包含用於篩選子元素的選擇器表示式的字串。

示例 1

在以下示例中,我們使用 children() 方法返回 <ul> 的直接子元素:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
        $("ul").children().css("color", "#40a944");
      });
  </script>
</head>
<body>
  <ul>Parent
    <li>children 1</li>
    <li>children 2</li>
    <li>children 3</li>
    <li>children 4</li>
  </ul>
</body>
</html>

當我們執行上述程式時,children() 方法將返回 <ul> 元素下的所有元素,並將它們的顏色更改為綠色。

示例 2

在這裡,我們選擇所有類為 'one' 的 li 元素,這些元素是其父 ul 元素的直接子元素:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
        $("ul").children(".one").css("color", "#40a944");
      });
  </script>
</head>
<body>
  <ul>Parent
    <li>child 1</li>
    <li class="one">child 2</li>
    <li class="one">child 3</li>
    <li class="second">child 4</li>
  </ul>
</body>
</html>

執行上述程式後,類為 'one' 的 li 元素將被返回,並且文字顏色為綠色。

示例 3

在下面的示例中,我們選擇所有作為其父 div 元素的直接子元素的 span 元素:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
        $("div").children("p").css("color", "#40a944");
      });
  </script>
</head>
<body>
  <div>Parent
    <p>paragraph: child</p>
    <span>span: child</span>
    <p>paragraph: child</p>
    <span>span: child</span>
    <p>paragraph: child</p>
  </div>
</body>
</html>

當我們執行上述程式時,children() 方法將返回所有作為 div 的直接子元素的 span 元素,並將它們的顏色更改為綠色。

jquery_ref_traversing.htm
廣告

© . All rights reserved.