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 JavaScript and the DOM (Retiring) Making Changes to the DOM Removing Nodes

Jake Kobs
Jake Kobs
9,215 Points

Why 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);
eslam said
eslam said
Courses Plus Student 6,734 Points

Because 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 :

            <h2>Things i like</h2>
            <ul>
                <li>Sports</li>
                <li>Games</li>
                <li>Books</li>
                <li>Travel</li>
            </ul>

            <h2>Countries i want to visit</h2>
            <ul>
                <li>Nepal</li>
                <li>Sweden</li>
                <li>China</li>
                <li>Russia</li>
            </ul>

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 :

            <h2>Things i like</h2>
            <ul>
                <li>Sports</li>
                <li>Games</li>
                <li>Books</li>
                <li>Travel</li>
            </ul>

            <h2>Countries i want to visit</h2>
            <ul>
                <li>Nepal</li>
                <li>Sweden</li>
                <li>China</li>
                <li>Russia</li>
            </ul>

let myList = document.querySelector('ul')

the browser will return only the first ul :

<ul>...</ul>
Jake Kobs
Jake Kobs
9,215 Points

Ohhh, 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
PLUS
eslam said
Courses Plus Student 6,734 Points

Check my answer i updated it with examples, and let me know if anything is still unclear