How to Remove Element with JavaScript and jQuery

In this tutorial, we will learn how to remove an HTML element from a page using pure JavaScript and jQuery.

 

Remove an Element With JavaScript

To remove an element with pure JavaScript, select it with a method such as getElementById(), then use the remove() method.

 

<div id="foo">Hello</div>
document.getElementById('foo').remove();

 

Remove Multiple Elements with a Class Name in Pure JavaScript

To remove multiple elements with a class name in pure JavaScript, select them with the getElementsByClassName() and store the result in a variable. Then use a while loop and remove each element at index 0 using the removeChild() method.

 

<div class="foo">Hello</div>
<div class="foo">Hello</div>
<div class="foo">Hello</div>
var elements = document.getElementsByClassName('foo');

while(elements[0]) {
  elements[0].parentNode.removeChild(elements[0]);
}

 

Remove an Element With jQuery

To remove an element with jQuery, use the remove() method. Let's create a button that will remove an element with an ID attribute when clicked.

 

<div id="foo">Hello</div>

<button type="button" id="bar">Remove</button>
$('#bar').click(function() {
  $('#foo').remove();
});

 

Remove Multiple Elements with jQuery

The remove() method can also remove multiple elements. Let's remove all elements with a class using jQuery:

 

<div class="foo">Hello</div>
<div class="foo">Hello</div>
<div class="foo">Hello</div>

<button type="button" id="bar">Remove</button>
$('#bar').click(function() {
  $('.foo').remove();
});

 

Remove and Reinsert an Element with jQuery

To remove an element and reinsert it later in the program, use the jQuery detach() method. It behaves in the same way as remove() except it allows us to store the element data for reinsertion.

 

<div id="foo">Hello</div>

<button type="button" id="bar">Remove</button>

 

$('#bar').click(function() {
  var foo = $('#foo').detach();

  $('button').after(foo);

  console.log($('#foo').text());
});
Hello

 

Result in the document:

 

<button type="button" id="bar">Remove</button>
<div id="foo">Hello</div>

 

In the above example, the #foo element is removed from the document and reinserted after the button element. After this operation, it can be used like any other element that was originally in the source code.

jquery