Difference between querySelector() and querySelectorAll()[0]

后端 未结 2 1880
旧巷少年郎
旧巷少年郎 2021-01-20 02:12

I ran across some JS code using the following to select the first of multiple nodes.

querySelectorAll()[0]

Isn\'t the following doing the e

2条回答
  •  时光取名叫无心
    2021-01-20 02:32

    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.

提交回复
热议问题