querySelector

Tutorial: DOM实战 Category: JS Published: 2026-04-07 13:58:26 Views: 20 Likes: 0 Comments: 0

H5 新增获取元素的方式

<!DOCTYPE html>
<html lang="en">
  <head></head>

  <body>
    <div class="box">盒子1</div>
    <div class="box">盒子2</div>
    <div id="nav">
      <ul>
        <li>首页</li>
        <li>产品</li>
      </ul>
      <ul>
        <li>首页</li>
        <li>产品</li>
      </ul>
    </div>

    <script>
      // 1. getElementsByClassName 根据类名获得某些元素集合
      var boxs = document.getElementsByClassName("box");
      console.log(boxs.length); // 2

      // 2. querySelector 返回指定选择器的第一个元素对象  切记 里面的选择器需要加符号 .box  #nav
      var firstBox = document.querySelector(".box");
      console.log(firstBox); // <div class="box">盒子1</div>

      var nav = document.querySelector("#nav");
      console.log(nav);

      var li = document.querySelector("li");
      console.log(li); // <li>首页</li>

      // 3. querySelectorAll()返回指定选择器的所有元素对象集合
      var allBox = document.querySelectorAll(".box");
      console.log(allBox); // [div.box, div.box]

      var lis = document.querySelectorAll("li");
      console.log(lis); // [li, li, li, li]
    </script>
  </body>
</html>