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

Calling the elements in order

Why do you have to call the parent first AND THEN call the child in the element? This is what I mean

let myList = document.querySelector('ul'); // call the parent

let firstListItem = document.querySelector('#first'); // call the child

myList.removeChild(firstListItem); // remove the child

can't you just use two lines of code and make it more "salty"? Can't it be like this?

let firstListItem = document.querySelector('#first');

firstListItem.removeChild(li);

1 Answer

You can never directly remove an item, you always need to navigate to it's parent and then delete it, it's just how JavaScript works. That's why it's .removeChild() and not remove

Okay? Then how do add a node that differs from the parent element?

const ulRemoveTest = document.querySelector('ul');

const removeLiTest = document.querySelector('p');

ulRemoveTest.removeChild('???????'); // what goes in here? ul:last-child?

You'd have to select the child element you want to delete then pass that in. The reason you have to do it this way is because the DOM is just an tree data structure. Just like a real tree you couldn't remove the branch you were sitting on.

Hopefully that helps.

-Ben