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

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!

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.