jquery
  1. jquery-detach

jQuery detach() Method

The detach() method in jQuery is used to remove an element from the DOM (Document Object Model) and store it in memory for later use. It is similar to the remove() method, but with the added ability to reinsert the element back into the DOM without having to recreate it.

Syntax

The basic syntax for using the detach() method is:

$(selector).detach();

Use

The detach() method is useful when you need to remove an element from the DOM temporarily and then reinsert it later. For example, you may want to remove an element from one part of the page and move it to another part of the page when a certain event occurs. Instead of creating a new element, you can simply detach and reinsert the existing element.

Example

Here is an example of using the detach() method in jQuery:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery detach() Method Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#detachButton').click(function() {
                $('#detachedDiv').detach();
            });

            $('#reattachButton').click(function() {
                $('#detachContainer').append($('#detachedDiv'));
            });
        });
    </script>
</head>
<body>
    <div id="detachContainer">
        <div id="detachedDiv">
            <p>Detached Div</p>
        </div>
    </div>
    <button id="detachButton">Detach</button>
    <button id="reattachButton">Reattach</button>
</body>
</html>
Try Playground

In this example, we have two buttons: one to detach the detachedDiv element from the DOM and one to reattach it. When the detach() method is called on the detachedDiv, it is removed from the page and stored in memory. When the reattachButton is clicked, the detachedDiv is appended back onto the page.

Summary

The jQuery detach() method is useful when you need to temporarily remove an element from the DOM and then reinsert it later. It is similar to the remove() method, but with the added ability to store the element in memory for later use. This allows you to move elements around the page without having to recreate them, saving time and resources.

Published on: