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) Getting a Handle on the DOM Select All Elements of a Particular Type

Vic Mercier
Vic Mercier
3,276 Points

getElementByTagName

<h1>JavaScript</h1> <h2>Html</h2> const myH = document.getElementByTagName("h"); alert(myH.lenght); Will it alert 2?

3 Answers

Steven Parker
Steven Parker
231,236 Points

You have a few issues here.

Owa makes a good point, but you have some other issues as well:

  • JavaScript code in an HTML document must be enclosed in <script> tags
  • you wrote "getElementByTagName" (singular) but the function is actually "getElementsByTagName" (plural)
  • you wrote "lenght" instead of "length"
Owa Aquino
Owa Aquino
19,277 Points

Hi Vic,

Sorry it will not alert 2 as a result. Because it can not find the 'h' because there is no such html element. The best way if you want to count the h1 and h2 element is to select their parent element and count its child element.

Hope this help.

Jeremy Castanza
Jeremy Castanza
12,081 Points

There's several ways to do what you're trying to do. Another way might be to add a class to each header and select by class using the getElementsByClassName method. As Owa Aquino mentioned though, you can't select "h" by itself.