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


Does querySelector use up more resources or take longer than using the other selectors getElementById, or getElementsByClassName?

I think they are more or less equally performant if you compare the right things. When you use querySelector and you do a query on a class than you should compare with getElementByClassName, if you do a query on an id, you should compare with getElementById.

1 Answer

An excellent question. Getting really technical, you'll have to read the specifications on both these functions since it's dependent on the JavaScript engine in use. StackOverflow on the getElementById methodology JavaScript Engines Long story short, querySelector no doubt requires more processing. This makes sense because of it's ability to process all kinds of selector strings which means a more complex function. The getElementById function is much simpler since it's more direct when searching; getElementById is only looking through IDs.

You can absolutely perform the test to determine the answer in your own case too. It would be interesting to run this test on different JavaScript engines (like testing on Chrome/Edge which uses V8 and Firefox which uses SpiderMonkey). You can use console.time('Label') and console.timeEnd('Label') to measure the speed of these functions.


Checking the console in Microsoft Edge DevTools reveals the result: QuerySelector: 0.067138671875 ms GetByID: 0.01708984375 ms

Note that these speeds can change depending on many, many other factors. You'll never get the same result, but you will notice that getElementById is faster.