jquery empty

What is jQuery empty() method?

jQuery empty() method is used to remove all the child elements and text content from the selected element(s). The method does not remove the selected element(s) itself, only its content.

Syntax:

$(selector).empty();

Example:

Consider the following HTML code:

<div id="myDiv">
    <p>This is a paragraph.</p>
    <ul>
        <li>List item 1</li>
        <li>List item 2</li>
        <li>List item 3</li>
    </ul>
</div>

If we call empty() method on the div element, all its child elements and text content will be removed, resulting in an empty div element:

$("#myDiv").empty();

The resulting HTML code will look like this:

<div id="myDiv"></div>

Multiple Ways to Use empty() Method:

  • We can pass a selector to empty() method to remove only the child elements that match the selector.
  • We can also pass a function to empty() method that returns the content to be removed. The function receives two arguments: index and html. Index is the index of the element being removed and html is the content of the element.

Using Selector:

Consider the following HTML code:

<div id="myDiv">
    <p>This is a paragraph.</p>
    <ul>
        <li class="item">List item 1</li>
        <li>List item 2</li>
        <li class="item">List item 3</li>
    </ul>
</div>

If we want to remove only the list items with class "item", we can pass the selector to empty() method:

$("#myDiv").find(".item").empty();

The resulting HTML code will look like this:

<div id="myDiv">
    <p>This is a paragraph.</p>
    <ul>
        <li></li>
        <li>List item 2</li>
        <li></li>
    </ul>
</div>

Using Function:

Consider the following HTML code:

<div id="myDiv">
    <p>This is a paragraph.</p>
    <ul>
        <li class="item">List item 1</li>
        <li>List item 2</li>
        <li class="item">List item 3</li>
    </ul>
</div>

If we want to remove only the list items whose content starts with "List item", we can pass a function to empty() method:

$("#myDiv").find("li").empty(function(index, html) {
    if (html.startsWith("List item")) {
        return html;
    }
});

The resulting HTML code will look like this:

<div id="myDiv">
    <p>This is a paragraph.</p>
    <ul>
        <li class="item"></li>
        <li></li>
        <li class="item"></li>
    </ul>
</div>

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe