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 trialJake Kobs
9,215 PointsWhy do we have [0] after the "document.getElementByTagName("ul")[0];"?
Why are we used brackets at the end of the statement? What's the purpose? Here's my code:
let myList = document.getElementsByTagName("ul")[0];
let firstListItem = document.querySelector("li");
myList.removeChild(firstListItem);
Jake Kobs
9,215 PointsOhhh, so it's basically stating to grab the first 'ul' tag in the code? Does the code in between also come along with it since it would be considered a child to 'ul'?
1 Answer
eslam said
Courses Plus Student 6,734 PointsCheck my answer i updated it with examples, and let me know if anything is still unclear
eslam said
Courses Plus Student 6,734 Pointseslam said
Courses Plus Student 6,734 PointsBecause getElementsByTagName will return a node list, so by adding ul[0] you will get the first ul in your document. if you want to get the first item of any tag you can use querySelector which will return only the first item.
Example #1 :
let myList = document.getElementsByTagName('ul')
the browser will return a node list or a collection :
HTMLCollection(2) [ul, ul]
if you want to select the first ul :
myList[0]
and if you want to select the second ul :
myList[1]
Example #2 :
let myList = document.querySelector('ul')
the browser will return only the first ul :
<ul>...</ul>