JavaScript JavaScript and the DOM Getting a Handle on the DOM Using CSS Queries to Select Page Elements

Sunny Chu
Sunny Chu
4,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?

3 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

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! :sparkles:

yk7
seal-mask
.a{fill-rule:evenodd;}techdegree
yk7
Full Stack JavaScript Techdegree Student 22,891 Points

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.
Sunny Chu
Sunny Chu
4,465 Points

Much thanks Youssef and Jennifer, this clears up my question alot!