SyntaxStudy
Sign Up
jQuery detach() for DOM Manipulation
jQuery Advanced 4 min read

detach() for DOM Manipulation

.detach() Pattern

Detach a complex element from the DOM before making many changes, then reattach — prevents repeated reflows during manipulation.

Example
// Detach large list from DOM
const $list = $("#big-list");
const $parent = $list.parent();
const $next = $list.next();
$list.detach(); // removes from DOM, keeps jQuery event bindings
// Make 500 changes off-screen (no reflow on each)
items.forEach(item => {
  $list.append(`<li class="item" data-id="${item.id}">${item.name}</li>`);
});
// Reattach in original position
if ($next.length) $next.before($list); else $parent.append($list);
Pro Tip

detach() differs from remove() — it preserves jQuery event handlers and data for the reattached element.