Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript equivalent of jQuery's .detach() function

Tags:

javascript

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?

like image 733
Jack Avatar asked Mar 22 '18 02:03

Jack


People also ask

What is the difference between remove () and detach () methods in jQuery?

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.

What does detach () method do?

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.

What is the JavaScript equivalent of $ () or jQuery ()?

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.

What is queryselector all in jQuery?

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.


1 Answers

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

like image 139
Vasyl Moskalov Avatar answered Oct 19 '22 12:10

Vasyl Moskalov