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 Interactive Web Pages with JavaScript Selecting Elements and Adding Events with JavaScript Perform: Selecting Elements

Zach Robinson
Zach Robinson
8,862 Points

Why are we using the getElementsByTagName method for the button functionality? Why not use an ID?

I understand the concept of using document.getElementsByTagName("button")[0]; I just don't understand why it's being used. Wouldn't it be more prudent to assign that button a particular ID, and then use the getElementById method instead? I just can't see how having an array of all the buttons on the page would be useful; other than when you're referencing the first button, wouldn't you have to manually rifle through your code and keep a numerical count of the button you want (like if I wanted to reference a button halfway through my code, wouldn't I have to manually find its index value by counting each button I see)?

If the reason we're doing this is simply because Andrew is trying to expose us to a new method that we may not have seen before, then please disregard this question - but if this method is preferred when scripting, can someone explain to me why?

2 Answers

Yes, it's mostly to show you another method, which could be useful if you only have access to change the JavaScript and not the HTML (say, if it was generated by some server-side scripting language by someone else).

Using an ID is also faster, though unless you're going to use it a lot, is unlikely to make a big difference.

I don't think he covers it in this course, but there are also newer methods available that are closer to the CSS/jQuery syntax for selecting elements on the page: .querySelector() and querySelectorAll().

Hi In one of the courses the instructor had said that it is best not to change the html file unless the element is being used very frequently.