在不知道父元素的情况下删除dom元素? [英] Remove dom element without knowing its parent?

查看:135
本文介绍了在不知道父元素的情况下删除dom元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以删除除body标签之外没有父元素的dom元素?我知道这对于像jquery这样的框架会很容易,但我试图坚持使用直接的javascript。

Is it possible to remove a dom element that has no parent other than the body tag? I know this would be easy with a framework like jquery, but I'm trying to stick to straight javascript.

以下是我发现的代码:

Here's the code I've found to do it otherwise:

function removeElement(parentDiv, childDiv){
     if (childDiv == parentDiv) {
          alert("The parent div cannot be removed.");
     }
     else if (document.getElementById(childDiv)) {     
          var child = document.getElementById(childDiv);
          var parent = document.getElementById(parentDiv);
          parent.removeChild(child);
     }
     else {
          alert("Child div has already been removed or does not exist.");
          return false;
     }
}   

谢谢!

推荐答案

你应该能够获得元素的父元素,然后从中删除元素

You should be able to get the parent of the element, then remove the element from that

function removeElement(el) {
el.parentNode.removeChild(el);
}

更新

您可以将其设置为HTMLElement上的新方法:

You can set this as a new method on the HTMLElement:

HTMLElement.prototype.remove = function() { this.parentNode.removeChild(this); return this; }

然后执行 el.remove()(也会返回元素)

And then do el.remove() (which will also return the element)

这篇关于在不知道父元素的情况下删除dom元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆