Removing elements In jQuery

remove method

The method remove([selector])removes elements from the DOM structure. For example, we have the following list:


<ul>
    <li class="lang">Java</li>
    <li class="lang">C/C++</li>
    <li class="lang">PHP</li>
    <li class="lang">JavaScript</li>
</ul>

We can remove all even elements of lists:

$('li:even').remove();

And the result will be the following list:

<ul>
    <li class="lang">C/C++</li>
    <li class="lang">JavaScript</li>
</ul>

We could also apply a selector to filter out elements to be removed:

$('li').remove(':even');

detach method

The method detachis similar to the remove method, except that when an object is removed, all data associated with it is preserved. The advantage of this approach is that we can later insert the removed element elsewhere in the html markup:

 
// remove the first element from the list, storing it in the item variable
var item = $('li:first').detach();
// insert it at the end of the list
$('ul').append(item);

empty method

The method emptyclears the contents of the elements, making them empty:

$('ul').empty();

As a result, all elements of the list will be removed, and the markup will contain an empty list: