HTML 如何检查带有 id 的元素是否存在

html how to check whether the element with id exist or not?

本文关键字:id 元素 存在 是否 何检查 检查 HTML      更新时间:2023-09-26

我按下一个按钮,使用 javascript 插入一个div,假设 id="exist"。最初,没有这样的元素。如何检查带 id 的元素是否存在?我使用了以下代码:

if(document.getElementById("tag_exist").innerHTML == "null")
        console.log("1111");

但它不会在控制台中打印出 1111,而是错误(未捕获的类型错误:无法读取 null 的属性"innerHTML"(。问题是它没有执行我需要运行的代码。如何检查带 id 的元素是否存在?

测试元素是否存在。不要获取元素,然后尝试读取您返回的任何内容的 innerHTML(因为如果元素不存在,这将引发异常(

if (document.getElementById("tag_exist"))

如果 id 不存在,则循环将执行该块

if (!document.getElementById("tag_exist")) {
// didn't exist
}

在访问任何属性或方法之前,应执行此操作。

if(document.getElementById("tag_exist")) {
  //exists
}

试试这个

if(document.getElementById("exist") != undefined) {
      //exists
}

代码中的问题是,如果没有id=tag_exits元素,浏览器引擎会抛出"无法从未定义读取 innerHTML 属性",或者什么都不会发生。发生这种情况是因为getElementById如果未找到元素,则返回undefined。

您可以选择编写:

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>