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()
Is there an advantage of using querySelectorAll()[0]
?
Both expressions will return the exact same result.
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.
So, theoretically, querySelector()
might be marginally more efficient than querySelectorAll()[0]
. However, their behaviour is identical.