Home > UI/UX Development > jQuery > jQuery: Difference between remove() and detach() methods

jQuery: Difference between remove() and detach() methods

This post was most recently updated on September 26th, 2017

Definition:

  • remove() – Removes all child elements with selected element. In this method you can restore all data but not event handlers of the removed elements from the DOM. All data and events related with elements will be removed.
  • detach() – Removes all child elements with selected elements. Even though it keeps all data and event handlers of the removed elements. This method is preferred to remove elements but it keeps copy of the removed elements which we can reuse at a later time.

Example:

HTML:

CODE:

Output:

DEMO

Explanation: In the above example there are SPAN element and some content inside the DIV element which is a “Yellow Box” and next to that is an empty “Red Box”. See there are three buttons remove(), detach() and attach.

Before click on any buttons click on “Yellow Box” you will get alert message “Yellow content box”. On the “Yellow Box” there is a click event with alert message. Now refresh browser to check button events.

To check difference between remove() and detach() methods follow the steps below:

First click on remove() button it will remove the Yellow box with inside elements data and events.

Then click on attach() you can see the removed “Yellow Box” attached inside the “Red Box” with content.

Now remember when you click on the “Yellow Box” there was an alert message “Yellow content box” click on yellow box to get this message again, you will not get alert message because remove() method removed event handlers from the selected elements.

Now refresh page and click on detach() button it will remove “Yellow Box”.

Then click on attach button “Yellow Box” will attach inside the “Red Box”.

Now click on “Yellow Box” you will get alert message “Yellow content box”

 

This Article is TAGGED in , , . BOOKMARK THE permalink.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">