Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.