JavaScript removeChild 不工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10433492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:52:40  来源:igfitidea点击:

JavaScript removeChild not working

javascriptremovechild

提问by Leandro Zhuzhi

I am using this JavaScript code to remove a couple elements from the page, but it's not working. When I inspect the code with Opera Dragonfly it says something like:

我正在使用此 JavaScript 代码从页面中删除几个元素,但它不起作用。当我用 Opera Dragonfly 检查代码时,它说的是:

Uncaught exception: Error: WRONG_ARGUMENTS_ERR

and points to the file and function name.

并指向文件和函数名。

The weird thing is that I use the exact same code in another function on the same page and it works without problem. The code is very small and simple:

奇怪的是,我在同一页面上的另一个函数中使用了完全相同的代码,并且它可以正常工作。代码非常小而简单:

var docBody = document.getElementById("body");
if(document.getElementById("marginDiv")){
  docBody.removeChild("marginDiv");
}

Both bodyand marginDivexist on the page. My goal is to make the thumbnails disappear when one clicks the background.

两者bodymarginDiv存在在页面上。我的目标是在单击背景时使缩略图消失。

回答by Niet the Dark Absol

You're trying to remove a string. A string is hardly an HTML element. You're also relying on marginDivbeing a direct child of body, which may not be the case.

您正在尝试删除字符串。字符串几乎不是 HTML 元素。您还依赖于marginDiv成为 的直接子代body,但情况可能并非如此。

Instead, try this:

相反,试试这个:

var remove = document.getElementById('marginDiv');
if( remove) remove.parentNode.removeChild(remove);

回答by Amberlamps

Try

尝试

docBody.removeChild(document.getElementById("marginDiv"));

回答by jenswirf

removeChildneeds a reference to a DOM element, not a string. Try this:

removeChild需要对 DOM 元素的引用,而不是字符串。试试这个:

var docBody = document.getElementById("body");
var marginDiv = document.getElementById("marginDiv");

if(marginDiv)){
docBody.removeChild(marginDiv);
}