本文已参与「新人创作礼」活动,一起开启掘金创作之路
- 访问元素节点主要依靠
document对象
document对象:可以理解为整个 HTML 文档,它是 DOM 节点树的根
接下来,让我们来了解一下 JS 常用的访问元素节点的方法:
1. document.getElementById()
通过id得到元素节点
举个例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>访问元素节点</title>
</head>
<body>
<div id="red">red</div>
<p id="blue">blue</p>
<script>
let red = document.getElementById('red');
console.log(red);
</script>
</body>
</html>
获取到了id为red的元素节点
2. document.getElementsByTagName()
通过标签名得到节点数组
标签名:例如 p,div 等这些元素名就是标签名
接下来,让我们通过一个例子理解一下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>访问元素节点</title>
</head>
<body>
<div>color</div>
<p>第一段元素</p>
<p>第二段元素</p>
<p>第三段元素</p>
<div>fruit</div>
<script>
let p = document.getElementsByTagName('p');
console.log(p);
</script>
</body>
</html>
获取到了标签名为p的节点数组
tips:
- 即使页面上只有一个指定标签名的节点,得到的也是一个长度为 1 的数组
3. document.getElementsByClassName()
通过类名得到节点数组
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>访问元素节点</title>
</head>
<body>
<div class="color">red</div>
<div class="color">green</div>
<div class="fruit">orange</div>
<div class="fruit">apple</div>
<div class="color">blue</div>
<script>
let colors = document.getElementsByClassName('color');
for (let color of colors) {
console.log(color);
}
</script>
</body>
</html>
得到类名为color的节点数组
4. document.querySelector()
通过选择器得到元素
选择器:CSS 的选择器
让我们通过一个例子看看:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>访问元素节点</title>
</head>
<body>
<div class="colors">
<div id="green">
green
</div>
<div id="red">
red
</div>
</div>
<script>
let red = document.querySelector('.colors #red');
console.log(red);
</script>
</body>
</html>
获取选择器名为.colors #red的元素
tips:
- 只能得到页面上一个元素,如果有多个元素符合条件,则只能得到第一个元素
5. document.querySelectorAll()
通过选择器得到元素数组
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>访问元素节点</title>
</head>
<body>
<div class="colors">
<div id="green">
green
</div>
<div id="red">
red
</div>
</div>
<script>
let colors = document.querySelectorAll('.colors div');
for (let color of colors) {
console.log(color);
}
</script>
</body>
</html>
将得到选择器名为.colors div的元素数组