03.DOM查询的其他方法.html 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <!DOCTYPE html>
  2. <html lang="en">
  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>Document</title>
  8. <script>
  9. window.onload = function () {
  10. //获取body标签
  11. // var body = document.getElementsByTagName("body")[0];
  12. // alert(body);
  13. /*
  14. 在document中有一个属性body,他保存的是body的引用
  15. */
  16. var body = document.body;
  17. console.log(body);
  18. /*
  19. document.documentElement保存的是html根标签
  20. */
  21. var html = document.documentElement;
  22. // alert(html);
  23. /*
  24. document.all代表页面中所有的元素
  25. */
  26. var all = document.all;
  27. // console.log(all);
  28. // console.log(all.length);
  29. // for (var i = 0; i < all.length; i++) {
  30. // console.log(all[i]);
  31. // }
  32. // all = document.getElementsByTagName("*");
  33. // console.log(all);
  34. // console.log(all.length);
  35. /*
  36. 根据元素的class属性值查询一组元素节点对象
  37. getElementsByClassName()可以根据class属性值获取一组元素节点对象,
  38. 但是该方法不支持IE8及以下的浏览器
  39. */
  40. // var box1 = document.getElementsByClassName("box1");
  41. // console.log(box1.length);
  42. //获取页面中的所有的div
  43. // var divs = document.getElementsByTagName("div");
  44. // console.log(divs.length);
  45. //获取class为box1中的所有的div
  46. //.box1 div
  47. /*
  48. document.querySelector()
  49. -需要一个选择器的字符串作为参数,可以根据一个CSS选择器来查询一个元素节点对象
  50. -虽然IE8中没有getElementsByClassName(),但是可以使用querySelector()代替
  51. 这个方法更加灵活
  52. -使用该方法总会返回唯一的一个元素,如果满足条件的元素有多个,那么它只会返回第一个
  53. */
  54. // var div = document.querySelector(".box1 div");
  55. // console.log(div);
  56. // console.log(div.innerHTML);
  57. // var box1 = document.querySelector(".box1");
  58. // console.log(box1);
  59. // console.log(box1.innerHTML);
  60. /*
  61. document.querySelectorAll()
  62. -该方法和querySelector()用法类似,不同的是它会将符合条件的元素封装到一个数组中返回
  63. -即使符合条件的元素只有一个,也会返回数组
  64. */
  65. var box1 = document.querySelectorAll(".box1");
  66. // console.log(box1.length);
  67. };
  68. </script>
  69. </head>
  70. <body>
  71. <div class="box1">
  72. <div>box1中的div</div>
  73. </div>
  74. <div class="box1">
  75. <div>box1中的div</div>
  76. </div>
  77. <div></div>
  78. </body>
  79. </html>