通过元素id来查找元素
创建一个按钮,通过id获取按钮节点对象
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button id="btn">这是按钮</button>
<script>
let btn = document.getElementById("btn");
console.log(btn);
</script>
</body>
</html>
通过标签名来查找元素
创建一个按钮,通过标签名获取按钮节点对象数组
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button>这是按钮</button>
<script>
let btn = document.getElementsByTagName("button");
console.log(btn);
</script>
</body>
</html>
通过类名来查找元素
创建一个按钮,通过标类名获取按钮节点对象数组
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button id="btn">这是按钮</button>
<script>
let btn = document.getElementByClassName("btn");
console.log(btn);
</script>
</body>
</html>
通过CSS选择器选择一个元素
创建一个按钮,通过CSS选择器选择该按钮
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button class="btn">这是按钮</button>
<script>
let btn = document.querySelector(".btn");
console.log(btn);
</script>
</body>
</html>
通过CSS选择器选择多个元素
创建一个无序列表,通过CSS选择器选择该列表的所有li
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<ul class="list">
<li>NO.1</li>
<li>NO.2</li>
<li>NO.3</li>
<li>NO.4</li>
</ul>
<script>
let list = document.querySelectorAll(".list li");
console.log(list);
</script>
</body>
</html>