博主信息
博文 29
粉丝 0
评论 0
访问量 35186
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
jQuery中的querySelector和querySelectorAll区别
咸鱼梦
原创
3917人浏览过

两者的区别:

这里引用w3c的解释

    querySelector:  return the first matching Element node within the node’s subtrees. If there is no such node, the method must return null .(返回指定元素节点的子树中匹配选择器的集合中的第一个元素,如果没有匹配返回null);

    querySelectorAll: return a NodeList containing all of the matching Element nodes within the node’s subtrees, in document order. If there are no such nodes, the method must return an empty NodeList. (按文档顺序返回指定元素节点的子树中匹配选择器的元素集合,如果没有匹配返回空集合);

从定义可以看querySelector和querySelectorAll的参数是CSS选择器字符串。区别在于querySelector返回的是一个第一个匹配元素,querySelectorAll返回的一个所有匹配元素集合(NodeList)。

用法:

<div class="text">
    <p>第一段文本</p>
    <p>第二段文本</p>
    <p>第三段文本</p>
    <p>第四段文本</p>
    <p>第五段文本</p>
    <p>第六段文本</p>
</div>
$(function(){
    var p = document.querySelector('p');//获取文档中首个p元素
    p.style.background = 'red';
});

执行结果:

QQ截图20171219170907.png

同上:

$(function(){
    var p = document.querySelectorAll('p');//获取文档中所有p元素
    console.log(p.length); //控制台输出为6
    for (var i=0; i<p.length; i++) {
        p[i].style.background = 'lightgreen'  //添加背景色
    };
})

执行结果:

QQ截图20171219172359.png

本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学