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) Making Changes to the DOM Styling Elements

querySelector vs getElementByClassName

In the video Guil used querySelector('.list') to select the <div> on the page.

However i used getElementByClassName('list'), but it didn't work as expected and it only selected the <p> nested within the <div>. Why didn't this select the whole <div> element which has the class = list??

Thanks

2 Answers

Steven Parker
Steven Parker
231,269 Points

The "getElementsByClassName" (note the spelling, with elements plural) method does not return a single element like "querySelector" does. Instead, it returns an HTMLCollection which is like an array..

But I'm not sure why this would have appeared to select a paragraph element. For a more precise answer, please show your complete code, or make a snapshot of your workspace and post the link to it here.

thanks for explaining that Steven. There's me thinking that the getElementByClassName would treat a <div> as one element, but yeah that makes sense if there's lots of elements contained in the <div>!

Had a small error in my code which was causing the <p> to disappear. Thanks!