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 trialtjeiosajfdksl
Courses Plus Student 8,981 PointsI get an undefined from console
I type in :
document.getElementsByClassName(".warning")[0]
at around 5minutes into video as per instruction but instead of what appears in video I get the message "undefined" returned o me . I am using Opera console. Can someone point out what is happening please?
2 Answers
Michael Hulet
47,913 PointsIn JavaScript's default methods, it takes class
es and id
s without their CSS selector characters. In the case of class
es, that's the period (.
) before the class name. In the code you wrote, JavaScript searches for a class
literally named .warning
instead of just warning
that you're actually looking for. The proper way to get all class
es of a specific name in vanilla JavaScript looks like this:
document.getElementsByClassName("warning"); // Notice the lack of a period (.) before warning
However, jQuery takes the CSS selector to search for elements. If this was jQuery, you would write it with a period (.
), like this:
$(".warning"); // Notice that a period *is* present here
tjeiosajfdksl
Courses Plus Student 8,981 PointsThank you for your explanation. I understand the 'why' now. Much appreciated.