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 trialCui Gunter
12,518 PointsgetElementsByClassName versus querySelector
In the bindTaskEvent function, I try using getElementsByClassName in place of querySelector just to experiment with a different command but nothing happens when I click on the button using the get method. I tried in the console for both the get and query method and both point to the same button. But only the querySelector method works when I click on the edit or delete button. I was curious as to why the getElementsByClassName did not work?
2 Answers
David Morisset
13,323 PointsI'm not sure what exercise you're talking about so i'll try to answer the best i can.
There are a few differences between querySelector and getElementsByClassname :
- getElementsByClassName returns a collection of elements while query selector returns only one element. You can access the element you want inside the collection by using bracket notation. In other words:
var myElem = document.querySelector(".myClass");
is equivalent to
var myElem = document.getElementsByClassName("myClass")[0];
Note that if more than one element matches the selector in querySelector, only the first one will get returned. If you want to return a collection, you should use querySelectorAll
From a syntax point of view, if you look at the previous examples, you'll notice that to select a class in querySelector, i did put a "." in front of myClass. this should not be done in getElementsByClassName.
querySelector and querySelectorAll return elements that are non-live while other selectors (getElementById, getElementsByClassName...) return live elements. So, elements of a collection returned by getElementsByClassName will be modified if they are modified in the DOM. Elements returned by querySelector will not.
I hope this helps
Cui Gunter
12,518 PointsThanks David.