我想知道querySelector和querySelectorAll对getElementsByClassName和getElementById的区别到底是什么?

从这个链接,我可以用querySelector收集,我可以写document.querySelector(".myclass")来获得类myclass的元素,文档.querySelector("#myid")来获得ID为myid的元素。但我已经可以做到getElementsByClassName和getElementById。应该优先选择哪一种?

我还在XPages中工作,其中ID是用冒号动态生成的,类似于以下视图:_id1:inputText1。所以当我写document.querySelector(“#view:_id1:inputText1”)时,它不起作用。但是写document.getElementById("view:_id1:inputText1")是有效的。知道为什么吗?


当前回答

querySelector和getlementbyID(Claassname,Tagname等)之间的主要区别是,如果满足条件的元素超过一个,querySelector将只返回一个输出,而getElementBy*将返回所有元素。

让我们考虑一个例子,让它更清楚。

 <nav id="primary" class="menu">
                            <a class="link" href="#">For Business</a>
                            <a class="link" href="#">Become an Instructor</a>
                            <a class="link" href="#">Mobile Applications</a>
                            <a class="link" href="#">Support</a>
                            <a class="link" href="#">Help</a>
   </nav> 

下面的代码将解释其中的区别

**QUERY SELECTOR**
document.querySelector('.link'); // Output : For Business (element)

document.querySelectorAll('.link'); //Out All the element with class link

**GET ELEMENT**
document.getElementsByClassName('link') // Output : will return all the element with a class "link" but whereas in query selector it will return only one element which encounters first.

简而言之,如果我们想选择单个元素,就选择queryslector,如果我们想选择多个元素,就选择getElement

其他回答

querySelector可以是一个完整的CSS(3)-Selector,包括id、类和伪类,如下所示:

'#id.class:pseudo'

// or

'tag #id .class .class.class'

使用getElementsByClassName,你可以定义一个类

'class'

使用getElementById,你可以只定义一个id

'id'

querySelector属于w3c Selector API

w3c室的十分

在我看来,最显著的区别是querySelectorAll的返回类型是静态节点列表,而getElementsBy的返回类型是活动节点列表。因此,演示2中的循环永远不会结束,因为lis是活动的,并且在每次迭代中更新自己。

// Demo 1 correct
var ul = document.querySelectorAll('ul')[0],
    lis = ul.querySelectorAll("li");
for(var i = 0; i < lis.length ; i++){
    ul.appendChild(document.createElement("li"));
}

// Demo 2 wrong
var ul = document.getElementsByTagName('ul')[0], 
    lis = ul.getElementsByTagName("li"); 
for(var i = 0; i < lis.length ; i++){
    ul.appendChild(document.createElement("li")); 
}

querySelector和querySelectorAll是一个相对较新的api,而getElementById和getElementsByClassName已经和我们在一起很长时间了。这意味着您使用什么主要取决于您需要支持的浏览器。

至于:,它有一个特殊的含义,所以如果你必须将它用作ID/类名的一部分,你必须转义它。

我来到这个页面纯粹是为了找出更好的方法来使用性能-即哪个更快:

querySelector / querySelectorAll or getElementsByClassName

我发现了这个: https://jsperf.com/getelementsbyclassname-vs-queryselectorall/18

它在上面的2个x例子上运行了一个测试,另外它还对jQuery的等效选择器进行了测试。我的测试结果如下:

getElementsByClassName = 1,138,018 operations / sec - <<< clear winner
querySelectorAll = 39,033 operations / sec
jquery select = 381,648 operations / sec

从Mozilla文档收集:

NodeSelector接口 该规范为任何实现Document、DocumentFragment或Element接口的对象添加了两个新方法:

querySelector

返回节点子树中第一个匹配的Element节点。如果 没有找到匹配的节点,返回null。

querySelectorAll

对象中所有匹配的Element节点 节点的子树,如果没有找到匹配则返回空的NodeList。

and

注意:querySelectorAll()返回的NodeList不是活的 意味着DOM中的更改不会反映在集合中。 这与返回live的其他DOM查询方法不同 节点列表。