How to use jQuery Remove Method for removing Elements from DOM

How to use jQuery Remove Method for removing Elements from DOM

When you want to remove an element from the DOM use jQuery Remove Method. The .remove() will remove elements along with its children.

Note: If you want to simply empty the element then you need to use the jQuery Empty method.

jQuery Remove – Removing a div along with its children

I have a div with 3 to p elements as its children.

<div id="div1">
    <p>United States</p>
    <p>New York</p>
    <p>New York City</p>
</div>

To remove this div along with all its children use .remove() method like this:

$("#div1").remove(); 

jQuery Remove – Filtering the Elements to be Removed

There are 3 p elements. Two of them have class abc while one does not have any class.

<p class="abc">Paragraph with class="abc"</p>
<p class="abc">Paragraph with class="abc"</p>
<p>Paragraph</p>

To remove p elements having class abc, you have to pass “.abc” inside the .remvoe() method.

$("p").remove(".abc"); 

Passing multiple filters

In the same way you can provide multiple filter parameters.

Suppose there are 3 p elements, first has class abc, second does not have any class, while the third has class xyz.

<p class="abc">Paragraph with class="abc"</p>
<p>Paragraph</p>
<p class="xyz">Paragraph with class="xyz"</p>

To remove p elements having class abc and xyz use the .remove() method like this.

$("p").remove(".abc, .xyz");

Download link:

DOWNLOAD

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate