document.getElementsByClassName('big');
返回是一个伪数组,根据类名来选择。
document.querySelector('.box'); css选择器
document.querySelector('#nav'); css选择器
document.querySelector('li'); css选择器
这个通杀,声明都能选,但是返回的是选中的第一个元素
document.querySelectorAll('box'); 返回的是集合
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="box">盒子1</div>
<div class="box">盒子2</div>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<script>
var box = document.getElementsByClassName('box');
// 返回第一个元素
var firstbox = document.querySelector('.box');
console.log(firstbox);
</script>
</body>
</html>点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号