• jQuery Video Tutorials

jQuery :empty Selector



The :empty selector in jQuery is used to select elements that do not have any child nodes, including text nodes. In other words, It selects elements that do not contain any child elements or text content.

Syntax

Following is the syntax of :empty selector in jQuery −

$(":empty")

Parameters

Following are the parameters of this method −

  • ":empty" − This selector selects the elements with no child nodes.

Example 1

In the following example, we are using the jQuery :empty selector to find the empty 'p' elements and set their text to "This paragraph was empty." −

<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>

After executing the above program, the provided text will be added to the empty <p> elements.

Example 2

In this example, we are finding the empty "li" elements and setting their text to "This list item is empty." −

<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>

After executing the above program, the provided text will be added to the empty <li> elements.

jquery_ref_selectors.htm
Advertisements