jQuery :empty 選擇器



jQuery 中的:empty選擇器用於選擇沒有任何子節點(包括文字節點)的元素。換句話說,它選擇不包含任何子元素或文字內容的元素。

語法

以下是 jQuery 中 :empty 選擇器的語法:

$(":empty")

引數

以下是此方法的引數:

  • ":empty" − 此選擇器選擇沒有子節點的元素。

示例 1

在下面的示例中,我們使用 jQuery :empty 選擇器查詢空的 'p' 元素並將它們的文字設定為“此段落為空”。

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function() {
      $('p:empty').text('This paragraph was empty.');
    });
  </script>
</head>
<body>
  <p>This paragraph has content.</p>
  <p></p>
  <p>This paragraph also has content.</p>
  <p></p>
</body>
</html>

執行上述程式後,提供的文字將新增到空的<p>元素中。

示例 2

在此示例中,我們查詢空的 "li" 元素並將它們的文字設定為“此列表項為空”。

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function() {
      $('li:empty').text('This list item is empty.');
    });
  </script>
</head>
<body>
  <ul>
    <li>Item 1</li>
    <li></li>
    <li>Item 3</li>
    <li></li>
  </ul>
</body>
</html>

執行上述程式後,提供的文字將新增到空的<li>元素中。

jquery_ref_selectors.htm
廣告
© . All rights reserved.