Home > OS >  How can I unappend an jQuery object from dom tree?
How can I unappend an jQuery object from dom tree?

Time:10-24

I'm explicity not looking for the remove() function.

A jQuery-Object not related to the DOM can be created using this:

let $element = $('<div>').addClass('myInvisibleDomObject').text('Test');

This unrelated object is appended on keypress to my DOM, but should be unappened when releasing the key.

I'm using this for an static object which represents the camera access. So my object is an video element, with stream data, video src, etc. So it's a little bit more complex than the code sample above. I do not want to clone the video object or create a new stream, because this is to slow.

I already tried appendTo(null), but this does not work. Simply hiding is no workaround, because some of the html is replaced via xhr requests on demand. I want a clean solution an no append to some other object like the <body> or something like this.

Example:

 // $element is the element from above
 // .cameraPreview is some div inside my DOM

 $(document).keydown(function(event: JQuery.Event) {
     $element.appendTo('.cameraPreview');
 });

 $(document).keyup(function(event: JQuery.Event) {
     $element.unappendFrom('.cameraPreview'); // this does not exist
 });

CodePudding user response:

How about .detach()?

The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

let attached = false;
let $container = $('#container');
let $element = $('<div>').addClass('myInvisibleDomObject').text('Test');

$('button').on('click', function() {

    if (attached) {
        console.log('detaching');
        $element.detach();
    } else {
        console.log('attaching');
        $container.append($element);
    }
    
    attached = !attached;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="container"></div>

<button>Attach/Detach</button>

  • Related