Reinsert a Detached jQuery Element into the DOM
Detaching an element using jQuery removes it from the Document Object
Model (DOM) while keeping all of its bound events and associated data
intact in memory. This guide demonstrates how to store a detached
element in a variable and reinsert it anywhere in the DOM using standard
jQuery insertion methods such as append(),
prepend(), before(), and
after().
Step 1: Detach and Store the Element
To reinsert an element later, you must capture the reference returned
by jQuery's .detach() method in a variable. Unlike
.remove(), .detach() retains all jQuery data
and event handlers associated with the removed elements.
// Select the element, detach it from the DOM, and save it to a variable
const $myElement = $('#my-element').detach();Step 2: Choose an Insertion Method
Once the element is stored in a variable, you can place it back into the document using any of jQuery's DOM insertion methods, depending on the desired placement relative to a target element.
1. Insert as the
Last Child (append or appendTo)
To place the detached element at the end of a parent container:
// Using append() on the target container
$('#container').append($myElement);
// Alternatively, using appendTo() on the detached element
$myElement.appendTo('#container');2. Insert as
the First Child (prepend or prependTo)
To insert the element at the beginning of a parent container:
// Using prepend() on the target container
$('#container').prepend($myElement);
// Alternatively, using prependTo() on the detached element
$myElement.prependTo('#container');3.
Insert as a Sibling (before, after,
insertBefore, or insertAfter)
To place the element adjacent to another element on the same hierarchy level:
// Insert directly before a sibling element
$('#sibling-element').before($myElement);
// or: $myElement.insertBefore('#sibling-element');
// Insert directly after a sibling element
$('#sibling-element').after($myElement);
// or: $myElement.insertAfter('#sibling-element');Complete Example
Here is a full example showing an element being detached, modified while off-screen, and then reinserted back into the DOM with its event listeners working:
// Attach a click event
$('#item').on('click', function() {
alert('Element clicked!');
});
// Detach the element from the DOM
const $detachedItem = $('#item').detach();
// Perform operations while detached (e.g., modifying text)
$detachedItem.text('Reinserted Item');
// Reinsert the element into a new container
$('#new-container').append($detachedItem);
// The click event remains active after reinsertion