JavaScript JavaScript and the DOM Traversing the DOM Parent Traversal

Peter Mercado
Peter Mercado
7,911 Points

Not sure what I am doing here!

const removeMe = document.querySelector('.remove_me'); let parent = removeMe.parentNode; parent.removeChild('removeMe');

app.js
const removeMe = document.querySelector('.remove_me');
let parent = removeMe.parentNode;
parent.removeChild('removeMe');
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Parent Traversal</title>
    </head>
    <link rel="stylesheet" href="style.css" />
    <body>
        <ul>
            <li>Hello</li>
            <li>Hi</li>
            <li class="remove_me">Good bye!</li>
            <li>Howdy</li>
        </ul>
        <script src="app.js"></script>
    </body>
</html>

1 Answer

Duy Duong
Duy Duong
7,458 Points

Hi Peter,

const removeMe = document.querySelector('.remove_me');

the querySelector() method will get you the first element with that class In this case, you get the first element of the "remove_me" class and set it to const removeMe

let parent = removeMe.parentNode;

After that, this line set 'parent' as the parent Node of the 'removeMe' we set before. In our case, it would be the <ul> element since the removeMe is an <li> element.

parent.removeChild('removeMe');

Finally, the removeChild() method allows you you to remove one child element with a specified name. So the <li> element with "remove_me" class will be deleted.

After the code runs, you should have the following codes in your HTML:

<ul>
            <li>Hello</li>
            <li>Hi</li>
            <li class="remove_me">Good bye!</li>
            <li>Howdy</li>
        </ul>
whatever ever
whatever ever
615 Points

but after task 2 , the task 1 becomes no longer passing..