Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between detach(), hide() and remove() - jQuery

What is the functional difference between these three jQuery methods:

  • detach()
  • hide()
  • remove()
like image 781
Vivek Avatar asked Feb 09 '11 06:02

Vivek


People also ask

What is the difference between Element ') remove () and Element ') detach ()?

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.

What is the use of detach in jQuery?

jQuery detach() Method The detach() method removes the selected elements, including all text and child nodes. However, it keeps data and events. This method also keeps a copy of the removed elements, which allows them to be reinserted at a later time.

Which jQuery method is used to hide?

5) Which of the following jQuery method is used to hide the selected elements? Explanation: The jQuery hide() method is used to hide the selected elements.


2 Answers

hide() sets the matched elements' CSS display property to none.

remove() removes the matched elements from the DOM completely.

detach() is like remove(), but keeps the stored data and events associated with the matched elements.

To re-insert a detached element into the DOM, simply insert the returned jQuery set from detach():

var span = $('span').detach();  ...  span.appendTo('body'); 
like image 158
Jacob Relkin Avatar answered Oct 18 '22 11:10

Jacob Relkin


Imagine a piece of paper on a table with some notes written with pencil.

  • hide -> throw a clothe onto it
  • empty -> remove the notes with an eraser
  • detach -> grab the paper in your hand and keep it there for whatever future plans
  • remove -> grab the paper and throw it to the dustbin

The table represents the current DOM space, the paper represents the element, and the notes represent the contents (child nodes) of the element.

A bit simplified and not completely accurate, but easy to understand.

like image 33
Zoltán Tamási Avatar answered Oct 18 '22 11:10

Zoltán Tamási