Sunny Chu4,465 Points
Is there is a reason to getElementByID/ClassName/TagName over querySelector?
It seems getElementByX can do, querySelector can also do and my code is more consistent to look at as well. Is there any practical reason why I want to use getElementByX?
Jennifer NordellTreehouse Staff
Hi there! Actually, there can be a reason to use it over
querySelector. When you have a
querySelector it requires a bit of additional parsing by the browser which could, potentially, affect the time it takes to run your code.
For instance, if you simply have an element with the id of "my-item" and you want to pick it and you don't need any extra traversal, you might opt for the
getElementById. However, if you need a more complicated traversal like all the paragraphs with a specific class name inside the element with the id of "my-item", a
querySelector might be more concise and easy to read.
I made this JSPerf test scenario where you can see the difference in run time.
While using the
querySelector is a bit slower here, I would say that it's still highly unlikely that you'd ever run into a significant difference. But that also depends a lot on the browser, the number of elements it has to parse and more.
Hope this helps!
Hello, Both of them will get you what you want.
- getElementByX; It's a little bit faster to get the X.
- querySelector, we can target more complex selectors.