jQuery detach() example

jQuery detach() function is used to remove the set of matched elements from the DOM.

Example - Detach all paragraphs from the DOM

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>detach demo</title>
    <style>
        p {
            background: yellow;
            margin: 6px 0;
        }

        p.off {
            background: black;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>

<body>

    <p>Hello</p>
    how are
    <p>you?</p>
    <button>Attach/detach paragraphs</button>

    <script>
        $("p").click(function() {
            $(this).toggleClass("off");
        });
        var p;
        $("button").click(function() {
            if (p) {
                p.appendTo("body");
                p = null;
            } else {
                p = $("p").detach();
            }
        });
    </script>

</body>

</html>
Try it Yourself - Copy paste code in Online HTML Editor to see the result

References


Comments