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

后端 未结 2 1864
旧巷少年郎
旧巷少年郎 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:46

    They both result in the same thing, but they take different routes (literally and figuratively) to get there. In your example, .querySelector() is the correct approach because .querySelectorAll() will incur more of a performance hit by scanning the entire element that the method is called on when it only needs to use the first match.

    The advantage to .querySelectorAll() is that you can cache a reference to the entire set of matched elements and then index them or loop them as needed later. So, if there was a need for the first matched element, but the entire set was going to be needed somewhere else in the code, then .querySelectorAll(<>)[0] would make sense.

提交回复
热议问题