querySelector()和querySelectorAll()[0]之间的区别 [英] Difference between querySelector() and querySelectorAll()[0]
问题描述
我使用以下代码选择了一些JS代码,以选择多个节点中的第一个.
I ran across some JS code using the following to select the first of multiple nodes.
querySelectorAll()[0]
下面的人不是在做同样的事情吗?
Isn't the following doing the exact same thing?
querySelector()
使用 querySelectorAll()[0]
是否有优势?
推荐答案
两个表达式都将返回完全相同的结果.
Both expressions will return the exact same result.
唯一的区别是 querySelectorAll()[0]
将首先找到与选择器匹配的所有项目,然后为第一个项目建立索引.而 querySelector()
一旦找到第一个元素就会短路".
The only difference is the querySelectorAll()[0]
will first find all the items that match the selector and then index the first item. Whereas querySelector()
will "short circuit" once it finds the first element.
因此,从理论上讲, querySelector()
可能比 querySelectorAll()[0]
效率略高.但是,它们的行为是相同的.
So, theoretically, querySelector()
might be marginally more efficient than querySelectorAll()[0]
. However, their behaviour is identical.
这篇关于querySelector()和querySelectorAll()[0]之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!