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 an Element from the DOM

Alex Parvis
Alex Parvis
4,464 Points

Remove list Item from the DOM

Who doesn't this command remove the list item?

<!DOCTYPE html>
        <title>DOM Manipulation</title>
    <link rel="stylesheet" href="style.css" />
            <li id="first">First Item</li>
            <li id="second">Second Item</li>
            <li id="third">Third Item</li>
        <script src="app.js"></script>
let myList = document.querySelector('ul');

let firstListItem = document.getElementById('li');


2 Answers

Hey Alex,

If you want to use getElementById, you need to select the correct ID for the first list item. In our case, the ID is first:

let firstListItem = document.getElementById('first');

You can also use querySelector, as the first list item only will be selected.

For removal, you'll want to call the removeChild method on myList and pass it the firstListItem variable.

// Select the unordered list
let myList = document.querySelector('ul');
// Select the first list item (First child of the unordered list)
let firstListItem = document.querySelector('li');
// Remove the first list item

Here are some problem, take them:


let firstListItem = document.getElementById('li');

There isn't any element by id: li, this id's is: "first.

So You can do that to slove: let listItem = document.getElementById('first');


First for You can remove the firstListItem add tu a parent for it after that You need to remove it's child, something like that:

myList.appendChild(firstListItem); //add parent myList.removeChild(firstListItem); //removes paarent's child, firstListItem.

I hope I can help You!