jquery
  1. jquery-empty

JQuery empty()

The empty() method in JQuery is used to remove all child nodes from the selected element(s). It does not remove the selected element(s) itself, only their children.

Syntax

$(selector).empty();

The $(selector) specifies the element(s) to be emptied.

Use

The empty() method is often used to reset or clear the content of an HTML element. It is commonly used in web applications that involve dynamic content or user input.

Example

Here is an example of using the empty() method in JQuery:

<!DOCTYPE html>
<html>
<head>
    <title>JQuery empty() Method Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#clearButton").click(function(){
                $("#myList").empty();
            });
        });
    </script>
</head>
<body>
    <h1>JQuery empty() Method Example</h1>
    <ul id="myList">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
    <button id="clearButton">Clear List</button>
</body>
</html>
Try Playground

In this example, we have a simple HTML list element with three list items. We also have a button that, when clicked, executes the empty() method on the list element. This removes all the list items from the list.

Summary

The empty() method in JQuery is a useful tool for removing the content of an HTML element. It is often used in web applications to reset or clear user input or dynamic content. With its simple syntax and ease of use, the empty() method is a valuable tool for any developer working with JQuery.

Published on: