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">

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

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


    how are
    <button>Attach/detach paragraphs</button>

        $("p").click(function() {
        var p;
        $("button").click(function() {
            if (p) {
                p = null;
            } else {
                p = $("p").detach();


Try it Yourself - Copy paste code in Online HTML Editor to see the result