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 trialNelson J
7,411 Pointsisn't selecting the li tag inside the ul tag, the same as selecting the elements inside an array, if so, why it loops?
This is what I mean:
/* Selects li and loops over it,
yet, it doesn't have lis inside
*/
const myList = document.getElementsByTagName('li');
/* Should be used
because ul actually has the lis inside
*/
const myList = document.getElementsByTagName('ul');
I used the ul and it works the same. confusing.
1 Answer
Steven Parker
231,236 PointsWhen you select something by tag name, you are referencing that item and not its contents. But you could get the items inside by using the "children" property. Also remember that "getElementsByTagName" returns a collection, even if it only contains one thing.
const myList = document.getElementsByTagName('li'); // the collection of all "li" elements
const myList = document.getElementsByTagName('ul')[0].children; // the same, "the hard way"
Note that these only do the same thing when there is only one ul on the page. Otherwise, the first still gets all li elements on the page, but the second only gets the ones inside the first ul.