I'm looking for a JavaScript function which does the same thing as jQuery's detach()
(detach an element from DOM without removing it). I came across this, but it's not an officially supported function. Does JavaScript have a function similar to .detach()
that is built in?
A selector expression that filters the set of matched elements to be removed. 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.
The detach () method removes the selected elements, including all text and child nodes. However, it keeps data and events. This method also keeps a copy of the removed elements, which allows them to be reinserted at a later time.
The equivalent to $ () or jQuery () in JavaScript is querySelector () or querySelectorAll (), which, just like with jQuery, you can call with a CSS selector. querySelectorAll () returns, just like jQuery does, an array of elements that you can work with.
Selecting one or several DOM elements to do something with is one of the most basic elements of jQuery. The equivalent to $ () or jQuery () in JavaScript is querySelector () or querySelectorAll (), which, just like with jQuery, you can call with a CSS selector.
Something like this?
function detach(node) {
return node.parentElement.removeChild(node);
}
or, even you can just use node.parentElement.removeChild(node)
Brief explanation. From MDN
The Node.removeChild() method removes a child node from the DOM. Returns removed node.
The removed child node still exists in memory, but is no longer part of the DOM. ... you may reuse the removed node later in your code....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With