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

Dennis Luks
Dennis Luks
1,305 Points

How do I know where the new task list element appears?

Hi everybody,

with following code a new task list element is being created:

var createNewTaskElement = function(taskString){ var listItem = document.createElement("li"); var checkBox = document.createElement("input"); var label = document.createElement("label"); var editInput = document.createElement("input"); var deleteButton = document.createElement("button"); var editButton = document.createElement("button");

listItem.appendChild(checkBox); listItem.appendChild(label); listItem.appendChild(editInput); listItem.appendChild(deleteButton); listItem.appendChild(editButton); return listItem; } addButton.onclick = addTask;

My question: How do I know / where or how can I manipulate where the new task list item appears?

Best greetings and happy holidays to you all, Dennis

1 Answer

var createNewTaskElement = function(taskString){ 
  var listItem = document.createElement("li"); 
  var checkBox = document.createElement("input"); 
  var label = document.createElement("label"); 
  var editInput = document.createElement("input"); 
  var deleteButton = document.createElement("button"); 
  var editButton = document.createElement("button");

  listItem.appendChild(checkBox); 
  listItem.appendChild(label); 
  listItem.appendChild(editInput); 
  listItem.appendChild(deleteButton); 
  listItem.appendChild(editButton); 

  return listItem; 

} 

addButton.onclick = addTask;

So what I would do here is create an element in your HTML like this

<div id="myElement">

</div>

and then use this code after you declare your function above

document.getElementById("myElement").appendChild(createNewTaskElement("test"));

Here, you're targeting the div element in your HTML in JavaScript, and taking what is returned by your function and appending it to the element.

With this method you can control the placement completely with HTML and CSS. All styles will be applied to these elements you're adding to the DOM.

Dennis Luks
Dennis Luks
1,305 Points

Thanks a lot for the great explanation! :)