JavaScript

How to Remove HTML Element from DOM Using JQuery

In web programming developers often face situations where it is required to remove either the entire HTML element or only the elements nested within a specified element. To accomplish these tasks with great ease there are certain jQuery methods available such as remove() and empty(). This write-up will guide you on how to use these methods to remove an HTML element with the help of relevant examples.

Remove an HTML element using jQuery

Apply the below-mentioned methods to remove elements in jQuery.

  1. remove()
  2. empty()

Here we have discussed the above-mentioned methods in-depth.

remove() Method

This method removes an HTML element and everything inside it, which includes any content, or elements nested within the specified element.

Example

Suppose you want to remove a <div> element including all the nested elements present inside it using the remove() method. Use the following code.

HTML

<div class="div" style="border: 2px solid black; height: 60px; width: 200px;">

<p>Some paragraph</p>

</div>

<br><button class="button1">Remove</button>

In the above HTML code, we have created a <div>, and inside that <div> we have nested a <p> element. Moreover, we have also created a button that will remove the <div> element.

jQuery

$(document).ready(function(){

  $(".button1").click(function(){

    $(".div").remove();

  });

});

Now we have applied the remove() method that will remove the entire <div> and all of its child elements.

Output


The remove() method has successfully removed the whole div.

empty() Method

The empty() method is also used for removing elements, however, this method only removes the content or the elements nested inside the specified element.

Example

To demonstrate the working of the empty() method, we are using the above example but now instead of applying the remove() method we will apply the empty() method.

jQuery

$(document).ready(function(){

  $(".button1").click(function(){

    $(".div").empty();

  });

});

In the above code, the empty() method is used that will remove only the content or elements nested inside the div.

Output

The nested elements inside the div have been removed successfully.

Conclusion

HTML elements can be removed using the two methods provided by jQuery which are; remove(), and empty(). The remove() method removes an HTML element and everything inside it, which includes any content, or elements nested within the specified element, meanwhile, the empty() method only removes the content or the elements nested inside the specified element. These methods are highlighted in detail in this guide, along with relevant examples.

About the author

Naima Aftab

I am a software engineering professional with a profound interest in writing. I am pursuing technical writing as my full-time career and sharing my knowledge through my words.