Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

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.

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