Detach And Attach An Element

By bhagwatchouhan
Detach And Attach An Element

Sometimes we need to remove an element from DOM and add it back at the desired location. The most common usage is to detach an absolute positioned element and append it at the end of the body to always keep it on top of other elements.

The below-mentioned code explains the process.

// Detach element from the current position and store in a variable

var element = jQuery( '#element-selector' ).detach();

// OR

var elements = jQuery( '.element-selector' ).detach();

// Now attach the element/elements to the end of body

jQuery( document.body ).append( element );

// OR

jQuery( document.body ).append( elements );

This is how we can detach either a single element or multiple elements from their position and then append them at the end of the body.

share on :

Profile picture for user bhagwatchouhan
bhagwatchouhan