Explain the differences between empty() remove() and detach() methods in jQuery
If you are building something and want to remove some HTML elements on click, hover, or on any event then you should know that jQuery can do it easily for us. There are three jQuery methods that help us to remove HTML elements with some slight differences. These methods are:
- remove() Method: It completely removes the selected elements from DOM. It also removes event handlers and data associated with the selected element. Data associated with the removed element can be restored but event handlers can’t be restored.
- detach() Method: It also removes the selected element along with all of its child elements but the copy of the removed elements is kept to reuse at a later time.
- empty() Method: It removes all the child elements from the selected element but does not remove the selected element itself.
Let’s understand this with an example:
Example 1: This example illustrates the use of remove() method.
As you can see from the above output screenshots that on clicking the remove button yellow block along with its child red block got removed.
Example 2: This example illustrates the use of detach() method.
As you can see when first we click the remove button it removed the container element and all of its child element but since detach() is used all event handlers and data is stored in the ,their,removed variable due to which we appended all removed element again in the body on clicking insert button.
Example 3: This example illustrates the use of empty() method.
As you can see that clicking the empty button removes child div from container div(which is a parent element) therefore red block got removed.
Difference between empty(), remove() and detach() methods:
|It removes the matched element and its child elements from DOM.||It removes the matched elements and its child elements from DOM.||It removes only the child element of the matched element.|
|It also removes all event handlers, data etc. present inside the matched element||It keeps data of the detached element and can be reused.||It removed data, event handlers etc. of child elements. Matched element and its data remain safe.|
|If an element got removed It cannot be inserted again in the DOM.||The detached element can be inserted again inside DOM very easily.||If an element is emptied its child elements cannot be inserted again.|