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 trialHassan Kotati
3,645 PointsUsing h1 for TagName
Since we can use "p" as a tag, could we use h1 like the the following? document.getElementsByTagName("h1")[1] I tryed it but it doesn't work
var fullName;
var lastName;
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1 id="full_name"><span class="first_name">Andrew</span> <span class="last_name">Chalkley</span></h1>
<script src="app.js"></script>
</body>
</html>
2 Answers
Michael Hulet
47,913 PointsIn JavaScript, array indexes start counting from 0. Therefore, to get the first (and only, it seems) h1
element on the page, you would use this code:
//Notice the 0, instead of a 1
document.getElementsByTagName("h1")[0];
Hassan Kotati
3,645 PointsIsn't "h1" [0] for first_name ? . Otherwise how would we access the first name using h1 Tag?
Michael Hulet
47,913 PointsIn your code, it would be getting both the span
with the class
"first_name
" and the span
with the class
"last_name
". Personally, if I was going to access the span
with the class
"first_name
", I'd just do the following:
document.getElementsByClassName("first_name")[0];
However, if you want to access it by going through the h1
, you could do something like this:
document.getElementsByTagName("h1")[0].getElementsByClassName("first_name")[0];