1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>获取元素</title>
  8. </head>
  9. <body>
  10. <p id="date">2022-02-11</p>
  11. <ul>
  12. <li>列表1</li>
  13. <li>列表2</li>
  14. <li>列表3</li>
  15. </ul>
  16. <script>
  17. let date = document.getElementById('date')
  18. /*
  19. * 返回伪数组li的集合,如果没有li伪数组元素就为空
  20. */
  21. let list = document.getElementsByTagName('li')
  22. let alter = document.getElementsByClassName('alter')
  23. // querySelector(选择器) 选择第一个匹配的对象
  24. let query = document.querySelector('.alter')
  25. // querySelectorAll(选择器) 选择所有匹配的对象
  26. let queryAll = document.querySelectorAll('.alter')
  27. console.log(date) // <p id="date">2022-02-11</p>
  28. console.dir(date) // 打印对象内容,显示对象属性和方法
  29. console.log(list) // [li, li, li] (伪数组)
  30. console.log(list[0]) // <li>列表1</li>
  31. console.log(alter) // [ul.alter, p.alter] (伪数组)
  32. console.log(alter[1]) // <p class="alter">alter</p>
  33. console.log(query) // <ul class="alter">...</ul>
  34. query = document.querySelector('#date')
  35. console.log(query) // <p id="date">2022-02-11</p>
  36. console.log(queryAll) // [ul.alter, p.alter] (伪数组)
  37. </script>
  38. </body>
  39. </html>

获取<body><html>

  1. let body = document.body
  2. console.log(body)
  3. let html = document.documentElement
  4. console.log(html)