Blogger Information
Blog 29
fans 0
comment 0
visits 29283
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
jQuery中的querySelector和querySelectorAll区别
咸鱼梦
Original
3487 people have browsed it

两者的区别:

这里引用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

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