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 trialMuhammad Rizwan
8,595 PointsWe 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
Chunwei Li
18,816 PointsHi 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!
Unsubscribed User
8,841 PointsWe 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>
Jack Blankenship
Full Stack JavaScript Techdegree Graduate 39,036 PointsMy guess is that there is more than one button on your page and therefore you can reference it in that way.
Aaron Munoz
11,177 PointsIf 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.