.detach() Pattern
Detach a complex element from the DOM before making many changes, then reattach — prevents repeated reflows during manipulation.
Detach a complex element from the DOM before making many changes, then reattach — prevents repeated reflows during manipulation.
// 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);
detach() differs from remove() — it preserves jQuery event handlers and data for the reattached element.