javascript JScript 检查元素是否存在并将其删除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21591235/
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
JScript Check if element exists and remove it
提问by howdybaby
I'm trying to write a simple function in javascript to check if an element exists in the DOM and if it does remove, and if it doesn't, append it to the page, so far i've got this
我正在尝试在 javascript 中编写一个简单的函数来检查元素是否存在于 DOM 中以及它是否删除,如果没有,将其附加到页面,到目前为止我已经得到了
if document.contains(document.getElementById("submitbutton") {
document.getElementById("submitbutton").remove();
} else {
lastDiv.appendChild(submitButton);
}
(lastDiv is just the div I want to append the div 'submitButton' to) Yet i'm getting the error "Uncaught ReferenceError: myFunction is not defined"
(lastDiv 只是我想将 div 'submitButton' 附加到的 div)但我收到错误“未捕获的 ReferenceError:myFunction 未定义”
Any help? I'm aware this is a very newbie question, sorry about that
有什么帮助吗?我知道这是一个非常新手的问题,抱歉
回答by Kevin Bowersox
There is a syntax error in the code, if
statements require parens
代码中有语法错误,if
语句需要括号
if (document.contains(document.getElementById("submitbutton"))) {
document.getElementById("submitbutton").remove();
} else {
lastDiv.appendChild(submitButton);
}