自定义属性

Tutorial: DOM操作 Category: JS Published: 2026-04-07 13:58:26 Views: 20 Likes: 0 Comments: 0
<!DOCTYPE html>
<html lang="en">
  <head></head>

  <body>
    <div id="demo" index="1" class="nav"></div>

    <script>
      var div = document.querySelector("div");

      // 1. 获取元素的属性值
      // (1) element.属性
      console.log(div.id); // demo

      //(2) element.getAttribute('属性')  get得到获取 attribute 属性的意思
      // 我们程序员自己添加的属性我们称为自定义属性 index
      console.log(div.getAttribute("id")); // demo
      console.log(div.index); // undefined
      console.log(div.getAttribute("index")); // 1

      // 2. 设置元素属性值
      // (1) element.属性= '值'
      div.id = "test";
      div.className = "navs";

      // (2) element.setAttribute('属性', '值');  主要针对于自定义属性
      div.setAttribute("index", 2);
      div.setAttribute("class", "footer"); // class 特殊 这里面写的就是class 不是classNam
      // <div id="test" index="2" class="footer"></div>

      // 3 移除属性 removeAttribute(属性)
      div.removeAttribute("index");
    </script>
  </body>
</html>