JavaScript JavaScript and the DOM Making Changes to the DOM Removing an Element from the DOM

Adil Ismaaeel
Adil Ismaaeel
3,881 Points

removing element from variable

Finally, remove the <li> element stored in firstListItem from the DOM.

If i go based on what i understand 'first' is the li that needs to be removed but I dont understand how to call it and remove it. Any help would be appreciated

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

1 Answer

First target the parent element and then select the child you want to remove. Your idea is right but you can't target ul.removeChild(li); because it could be any ul or li. That's why you selected it first and stored in the variables myList and firstListItem.

myList.removeChild(firstListItem);

let li = document.querySelector('first'); <--- this is unnecessary since you already targeted #first with firstListItem.