jQuery Remove Elements: remove, empty, detach

To delete elements from the page, jQuery has a few methods. They look similar, but they do different things.

MethodWhat it does
.remove()Removes the element and everything inside it, with its data and events
.empty()Removes only the children of the element. The element stays
.detach()Removes the element, but keeps its data and events, so you can put it back
.replaceWith()Replaces the element with new content
<div id="box">
  <p class="a">One</p>
  <p class="b">Two</p>
  <p class="c">Three</p>
</div>

remove()

$('.a').remove();
HTML after the code runs

<div id="box">
<p class="b">Two</p>
<p class="c">Three</p>
</div>

You can give a selector to filter which elements to remove: $('p').remove('.b') removes only the paragraphs which have the class b.

$('p').remove('.b');
HTML after the code runs

<div id="box">
<p class="a">One</p>
<p class="c">Three</p>
</div>

empty()

$('#box').empty();
console.log('children left: ' + $('#box').children().length);
console.log('box still exists: ' + ($('#box').length === 1));
Console output

children left: 0
box still exists: true

detach() and put it back

<ul id="menu"><li id="item">Menu item</li></ul>
<div id="store"></div>
var $item = $('#item');
$item.on('click', function () { console.log('clicked'); });

var $removed = $item.detach();
console.log('in the menu: ' + $('#menu li').length);

$('#menu').append($removed);
console.log('in the menu again: ' + $('#menu li').length);
$('#item').trigger('click');
Console output

in the menu: 0
in the menu again: 1
clicked

The click handler still works after the item is put back. With .remove() the handler would be lost.

replaceWith()

<h3 id="title">Old title</h3>
$('#title').replaceWith('<h2 id="title">New title</h2>');
HTML after the code runs

<h2 id="title">New title</h2>

Remove an attribute or a class (not the element)

  • .removeAttr('title') removes an attribute.
  • .removeClass('active') removes a class.
  • .removeData('key') removes stored data.

Remove a row from a table

<table id="t">
  <tr><td>Row 1</td><td><button class="del">Delete</button></td></tr>
  <tr><td>Row 2</td><td><button class="del">Delete</button></td></tr>
</table>
$('#t').on('click', '.del', function () {
  $(this).closest('tr').remove();
});

$('.del').eq(0).click();
console.log('rows left: ' + $('#t tr').length);
Console output

rows left: 1

Here we use event delegation and closest('tr') to find the row of the button. See Event Delegation.

Note: .remove() is the one you need in most cases. Use .detach() when you will use the same element again. Next: CSS Classes.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.