[英]html how to check whether the element with id exist or not?
我按下一个按钮,使用javascript插入一个id为“ exist”的div。 最初,没有这样的元素。 如何检查ID为ID的元素是否存在? 我使用了以下代码:
if(document.getElementById("tag_exist").innerHTML == "null")
console.log("1111");
但是它不会在控制台中打印出1111而是错误(Uncaught TypeError:无法读取null的属性'innerHTML')。 问题在于它不执行我需要运行的代码。 如何检查ID为ID的元素是否存在?
测试元素是否存在。 不要获取元素,然后尝试读取返回的内容的innerHTML(因为如果元素不存在,则会抛出异常)
if (document.getElementById("tag_exist"))
在访问任何属性或方法之前,您应该这样做。
if(document.getElementById("tag_exist")) {
//exists
}
如果id不存在,则if循环将执行该块
if (!document.getElementById("tag_exist")) {
// didn't exist
}
尝试这个
if(document.getElementById("exist") != undefined) {
//exists
}
您的代码中的问题是,如果没有id=tag_exits
元素,浏览器引擎将抛出“无法从未定义中读取innerHTML属性”,否则什么也不会发生。 发生这种情况的原因是,如果未找到任何元素,则getElementById返回未定义。
您可以选择编写:
if((document.getElementById("tag_exist") || {}).innerHTML == null)
// code
要么
if((document.getElementById("tag_exist"))
// code
最后选择代表:
if((document.getElementById("tag_exist") !== undefined && (document.getElementById("tag_exist") !== null))
// code
通过在元素上调用innerHTML属性,您将做出假设,或更具体地说,浏览器中的javascript引擎正在做出的假设是该标记已存在。 但事实并非如此,相反您会得到预期的错误。 无法读取null的属性“ innerHTML”。 正如@Quentin所建议的那样,正确的方法是实际查看您要查找的元素是否存在。 if检查是真假检查,它只是说元素对象是否存在,它将返回true,否则,则返回false。 看到我的代码示例可能会使它更清晰一些。 ( 更容易在JSBIN上测试 )
<!DOCTYPE html>
<html>
<head>
<title>Demonstrate ID exists tag checking</title>
</head>
<body>
<!-- tag doesnt exist yet. Click button it creates a div.
second time you click the button console message displayed. -->
<button onclick="addDiv()">Add a div with id='tag exist'</button>
<script>
function addDiv() {
if(document.getElementById("tag_exist")) {
// do nothing div already exists
console.log("Div with id='tag_exists' already");
} else {
// append the div to body
var div = document.createElement("div");
div.setAttribute("id", "tag_exist")
div.innerHTML = "I now exist";
document.body.appendChild(div);
}
}
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.