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

JS document.querySelectorAll and document.querySelector();

Why are there other selectors like 'getElementById' and 'getElementsByTagNames' when the methods of document.querySelectorAll and document.querySelector(); exist?

Just wondering since the document.querySelectorAll and document.querySelector(); are so useful, why do we need more? Pro and Cons if anyone has any idea?

1 Answer

Theoretically they might be slightly faster since they don't need to parse CSS selectors to figure out what you are looking for, but the main reason they exist is the simple fact that they were the first selector methods added to JavaScript.

querySelector and querySelectorAll were added at a later time exactly because the getElement(s)ByX methods were a bit too limited and inconvenient to use. Because of that they are not supported by older browsers like IE6 and 7.

Unless you need to support older browsers I personally feel that using querySelector and querySelectorAll for all selection is perfectly acceptable.