比较通过id和class获取元素的区别
/*设置CSS样式*/
<style>
#box{
width: 200px;
height: 200px;
background-color: red;
}
</style>
<div id="box" class="box" title="ahahah">
盒子
</div>
1、通过id获取页面元素
/*输出box的title属性*/
<script>
var box=document.getElementById('box');
console.log(box.getAttribute('title'))
</script>
2、通过class获取页面元素
/*输出box的title属性*/
<script>
var box=document.querySelectorAll('#box');
console.log(box[0].getAttribute('title'))
</script>
总结:两者的区别在于,通过querySelectorAll获取页面元素得到的是一个伪数组,哪怕伪数组中只有一个元素,也需要加上对应的索引