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 Interactive Web Pages with JavaScript Traversing and Manipulating the DOM with JavaScript Perform: Appending and Removing Elements

Luciano Bruzzoni
Luciano Bruzzoni
15,518 Points

Is the code provided here to redundant or unnecessary?

Hello, I was wondering if the way Andrew coded the deleteTask function was kind of unnecessary.

var deleteTask = function(){
   var listItem = this.parentNode;
   var ul = listItem.parentNode;

   ul.removeChild(listItem);
}

I was able to reach the same functionality by just saying

var deleteTask = function(){
    this.parentNode.remove();
}

since (this) is the button and the parent is the list item, one doesn't need to get the parent and then the parent of the parent to then get the child when we just had what we wanted with the first parent. So I was wondering if it's best practice to do it the long way or was he just showing it that way to show different ways of traversing the DOM. Thanks!

Dennis de Vries
Dennis de Vries
9,440 Points

I was wondering the exact same thing here. It feels like when you tell someone to go to the second floor of a building by explaining it as: "Take the stairs up to the second, then go up to the third and take the stairs down one floor."

I totally get this is clearer for teaching purposes, but I just wanted to know if there is indeed a faster way. Thanks.

1 Answer

James Griffis
James Griffis
281 Points

In my opinion Andrew's example explains how the function operates and it does make the code easier to understand if an outsider was to come in and try to see what is exactly happening if they are unfamiliar with the application. That said making less work for yourself and doing it in fewer SLOC would usually be preferable if it replicates the results exactly and if possible, I have also found it quite helpful in allot of situations to do it the long way to fully understand a particular issue or unexpected behaviour. In a learning environment such as this i believe its generally best to use the long method to thoroughly explain the reasons for taking an action or making a decision within an application.

Im no expert more of an Enthusiastic amater at this stage but i hope this helps :)