Removing elements

Sometimes you might need to remove elements that are no longer needed. If you want to remove a set of elements and all their content, you can use the remove() method, whose syntax is as follows.

Method syntax: remove
remove([selector])
Removes all elements and their content in the set from the page, including event listeners attached and any data stored
Parameters
selector(String) An optional selector that further filters which elements of the set are to be removed
Returns
The jQuery collection

Note that as with many other jQuery methods, the set is returned as the result of this method. The elements that were removed from the DOM are still referenced by this set (and hence are not yet eligible for garbage collection) and can be further operated upon using other jQuery methods including appendTo()prependTo()insert-Before()insertAfter(). But any data stored or event listener added to the removed element is lost.

If you want to remove the elements from the DOM but retain any bound events and data (that you might have added using the data() method), you can use detach().

Method syntax: detach
detach([selector])
Removes all elements and their content in the set from the page DOM, retaining any bound events and jQuery data
Parameters
selector(Selector) An optional selector string that further filters which elements of the set are to be detached
Returns
The jQuery collection.

The detach() method is the preferred means of removing an element that you’ll want to put back into the DOM at a later time with its events and data intact. A typical situation pulls the element from the DOM, applies several changes to it, and then pushes it again in the DOM. Doing so will improve the performance of your code because modifying a detached element is faster than applying all the changes to one or more elements that are currently in the DOM.

To completely empty DOM elements of their contents but retain the elements themselves, you can use the empty() method. Its syntax is as follows.

Method syntax: empty
empty()
Removes the content of all DOM elements in the matched set.
Parameters
none
Returns
The jQuery collection.

This method is useful when you deal with injecting external content fetched using Ajax. Let’s say that you fetched some new content and now you need to add it inside your page in a <div> having content as its ID. You can perform this task with the following code:

Remember to pay attention when you inject external content inside your page using the html() method because you may be exposed to attacks such as XSS (cross-site scripting) and CSRF (cross-site request forgery).

Removing elements is nice, but sometimes you need to clone elements.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *