最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript equivalent of jQuery's .detach() function - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Mar 22, 2018 at 2:00 JackJack 4372 gold badges6 silver badges18 bronze badges 4
  • Does JavaScript have a function similar to .detach() that is built in?: Answer: No. – Randy Casburn Commented Mar 22, 2018 at 2:03
  • Don't forget jQuery is a Javascript library. You could read the source code of jQuery's detach function and try re-implement the behaviour. – ncphillips Commented Mar 22, 2018 at 2:07
  • github.com/jquery/jquery/blob/… – Randy Casburn Commented Mar 22, 2018 at 2:11
  • Just to be more (perhaps excruciatingly and unnecessarily) precise about this, JavaScript itself doesn't have any methods for manipulating the DOM at all. It's the DOM that provides such methods. The better question would be if there's a standard DOM method similar to jQuery's detach. – kshetline Commented Mar 22, 2018 at 2:12
Add a comment  | 

1 Answer 1

Reset to default 24

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

发布评论

评论列表(0)

  1. 暂无评论