PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 27, 2022

[FIXED] How can I unappend an jQuery object from dom tree?

 October 27, 2022     jquery, typescript     No comments   

Issue

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
 });

Solution

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>



Answered By - Don't Panic
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing