jquery
  1. jquery-remove

JQuery remove()

The remove() method in the jQuery library is used to remove the selected elements from the DOM (Document Object Model).

Syntax

The basic syntax for remove() method is as follows:

$(selector).remove();

In this syntax, the selector specifies the element(s) to be removed from the DOM.

Use

The remove() method in jQuery is useful when you want to remove an element from the DOM, as well as all its child elements and bound events. This method is also useful when you want to free up memory and improve performance by removing unused elements from the DOM.

Example

Here is an example of using the remove() method in jQuery:

<!DOCTYPE html>
<html>
<head>
    <title>JQuery Remove Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1 id="heading">Welcome to my website</h1>
    <p>This is a paragraph about my website.</p>
    <button onclick="removeElement()">Remove Heading Element</button>
    <script>
        function removeElement() {
            $("#heading").remove();
        }
    </script>
</body>
</html>
Try Playground

In this example, we have included the jQuery library and created a button that calls the removeElement() function when clicked. This function uses the remove() method to remove the h1 element with the ID heading when the button is clicked.

Summary

The remove() method in jQuery can be used to remove elements from the DOM, as well as any child elements and bound events. It is useful when you want to free up memory and improve performance by removing unused elements from the DOM. Use it in your next project to make your website more efficient and user-friendly.

Published on: