Blogger Information
Blog 33
fans 0
comment 2
visits 42261
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
使用querySelector()与querySelectorAll() 获取页面元素
hanyufeng的博客
Original
759 people have browsed it

函数说明:

querySelector():获取第1个元素

querySelectorAll():获取元素列表

实例代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>querySelector和querySelectorAll方式</title>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>

<ul>
    <li>HTML</li>
    <li>CSS</li>
    <li>JavaScript</li>
</ul>
<h3>设置一个元素的样式</h3>
<button>querySelector方式</button>
<button>querySelectorAll方式</button>
<h3>批量设置多个元素的样式</h3>
<button>querySelectorAll方式</button>

<script>

    var btn1 = document.getElementsByTagName('button')[0];
 btn1.onclick = function () {
        //QuerySelector方法,自动选取li数组的第1个元素
 //返回的是一个对象,不是数组
 document.querySelector('li').style.background = 'yellow';
 //等价于:
 // var li = document.getElementsByTagName('li')[0];
        // li.style.background = 'yellow';
        // 或者 document.getElementsByTagName('li')[0].style.background = 'yellow';
 }

    var btn2 = document.getElementsByTagName('button')[1];
 btn2.onclick = function () {
        //querySelectorAll方法,返回的是数组,加下标访问
 document.querySelectorAll('li')[0].style.background = 'green';
 }

    var btn3 = document.getElementsByTagName('button')[2];
 btn3.onclick = function () {
        //querySelectorAll方法,返回的是数组
 //循环遍历访问
 var lis = document.querySelectorAll('li');
 for (var i = 0; i < lis.length; i++) {
            //循环体内容
 lis[i].style.background = 'blue';
 }
    }
</script>
</body>
</html>

效果图:

q1.png




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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!