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

Muhammad Rizwan
Muhammad Rizwan
8,595 Points

We did not create any array how can we use following code? var addButton= getElementsByTagName('button')[0];

We did not create any array how can we use following code? var addButton= getElementsByTagName('button')[0];

4 Answers

Hi Muhammad,

Please refer to the below documents:

https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByTagName

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection

var elements = document.getElementsByTagName(name);

elements is a live HTMLCollection in the order they appear in the DOM tree.

The HTMLCollection interface represents a generic collection (array) of elements (in document order) and offers methods and properties for selecting from the list.

So, what getElementsByTagName function returns is an array.

Hope this is useful for your question.

Thanks!

Aishu P
Aishu P
8,841 Points

We accessed the elements "new-Task", "incomplete-tasks", "completed-tasks" using their ID Names which is unique (i.e) only "One" element will be present with the particular ID Name. So we used the method "getElementbyID()" which returns a single element.

To access the add Button :

  • there is no ID Name present, so we cannot use the method "getElementbyID()".
  • we had to use the Method "getElementsbyTagName()" . This method returns an array of elements . There are multiple buttons in the document. To access the first button in the document (add button), we use getElementsByTagName('button')[0] .

If we use getElementsByTagName('button')[1], it returns the next button(2nd) in the document.

<button class="edit">Edit</button>

Aaron Munoz
Aaron Munoz
11,177 Points

If you type in this code in the console in chrome

document.getElementsByTagName("button");

you will get an array of all the buttons in the document and the Add Button is the first one. And in programming, we start off counting from 0.