Removing elements In jQuery

remove method

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

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

We can remove all even elements of lists:


And the result will be the following list:

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

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


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

empty method

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


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