Blogger Information
Blog 12
fans 0
comment 0
visits 12827
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
JS中使用querySelector和querySelectorAll
留情的博客
Original
967 people have browsed it


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用querySelector来获取元素</title>
</head>
<body>
<ul>
    <li>早上去吃饭</li>
    <li>中午去吃饭</li>
    <li>晚上去吃饭</li>
</ul>
<button>点击</button>
<script>
 var btn = document.querySelector('button') //选择页面中的第一个button querySelector默认的就是返回页面的中 的第一个button元素
 btn.onclick = li;
 function li() {
 // 由于querySelectorAll获取的是页面中所有的li元素,所以在querySelectorAll('li')后需要加上[0]
 document.querySelectorAll('li')[0].style.backgroundColor="red"
 }
</script>
</body>
</html>

如果要全选li元素,还是需要遍历,只是选取的时候用了querySelectorAll语句

<script>
    var li = document.querySelectorAll('li')
    var btn = document.querySelector('button')
    btn.onclick = function () {
        for (var i=0;i<li.length;i++)
            li[i].style.backgroundColor = "red"
    }
</script>


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post