javascript中getElement*与querySelector*的区别

javascript中getElement*与querySelector*的区别

十一月 03, 2020

javascript中getElementById与querySelector的区别

写在前面

自从用了querySelector*一直以为querySelector*getElement*一类的好用多了,直到今天

正篇

querySelector* getElement*
更便捷 速度更快
不支持以数字开头的搜索
支持多级查找
静态 动态

多级查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<ul>
<li></li>
</ul>
</body>
<style>
</style>
<script>
window.onload = function(){
var ul = document.querySelector('ul');
var list = ul.querySelectorAll('li');
for(var i = 0; i < 3; i++){
ul.appendChild(document.createElement('li'));
}
console.log(list.length)
// 输出 1
// 注: 测试时 两段代码分别执行
// var ul = document.getElementsByTagName('ul')[0];
// var list = ul.getElementsByTagName('li');
// for(var i = 0; i < 3; i++){
// ul.appendChild(document.createElement('li'));
// }
// console.log(list.length)
// // 输出 4
}
</script>
</html>