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

listItem? affects of a global variable

I was watching this and it ocurred to me could we not make listItem a global variable and still do var listItem=this.parentNode;

and just go ahead and just say this at each append


or would that mess up the code?

1 Answer

Hey Aaron,

You could cache the variable listItem in the global context and then assign a new value each time a different function is called. You'd just have to initialize listItem (by just typing var listItem;) outside of the functions (preferably at the top of the script to avoid compiler problems), and then take away the var keyword from each listItem variable created in each function because we don't want any confusion between the global listItem variable and possible local listItem variables. i.e.

var taskInput = document.getElementById("new-task"); //new task
var addButton = document.getElementsByTagName("button")[0]; //first button, index 0
var incompletedTasksHolder = document.getElementById("incomplete-tasks"); //ul with id of #incomplete-tasks
var completedTasksHolder = document.getElementById("completed-tasks"); //ul id of #completed-tasks
var listItem;

//New Task list Item
var createNewTaskElement = function(taskString) {
  //Create List Item
  listItem = document.createElement("li");