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) Traversing the DOM Getting the First and Last Child

I would like to know what exactly is the difference between querySelector and querySelectorAll against .............????

I would like to know what exactly is the difference between querySelector and querySelectorAll against getElementsByClassName and getElementById and getElementsbyTagName..??? A detailed answer would be very much appreciated ..!

1 Answer

Steven Parker
Steven Parker
231,271 Points

These all return either a single element or collection of elements, but get them different ways:

  • querySelector returns the first single element in the document that matches the CSS-type selector
  • querySelectorAll returns a collection of all elements in the document that match the selector
  • getElementsByClassName returns a collection of elements that have the specified class (not a selector)
  • getElementById*returns the single element in the document that has the specified ID (there can only be one)
  • getElementsbyTagName returns a collection of elements that have the specified tag name (type)

The methods using CSS-type selectors are newer and more versatile.

Click on any of the names to go to the MDN documentation page for full details on the function.