markberning
1/8/2018 - 9:13 AM

Insert Elements into the DOM

// Insert Elements into the DOM
// Use document.createElement('li') and then store in a var.
var todoLi = document.createElement('li');

// First grab the element parent or sibling where you will be placing the new element, e.g. ul, and store it in a var.
var todosUl = document.querySelector('ul')

// Add an <li> to the <ul> by using appendChild()
todosUl.appendChild(todoLi);

//-----------------------------------------------------------------
// To print an array of items as new <li> items
// Grab and then clear the <ul>:
var todosUl = document.querySelector('ul');
      todosUl.innerHTML = '';
      
// Cylce thru array with for loop appending the li each cycle
// And set the innerHTML to a value in the object/array
for (var i=0;i<todoList.todos.length;i++){
  var todoLi = document.createElement('li');
  todoLi.innerHTML = todoList.todos[i].todoText;
  todosUl.appendChild(todoLi);
}

//------------------------------------------------------------------
// Use a function to create the element and then call the function elsewhere
createDeleteButton: function(){
    var todoDeleteButton = document.createElement('button');
    todoDeleteButton.textContent = 'Delete';
    todoDeleteButton.className = 'deleteButton';
    return todoDeleteButton;
  }
  
todoLi.appendChild(this.createDeleteButton());

// If buttons are to be added for each li in an ul...
// Add just a single event listener to the parent <ul> instead of an event listener for each and every <li>
// In order to run an event listener on a parent item we need the 'event' object from the click. That event object wii give us tons of info but the one we want is "target".
// "Target" tell us which element we clicked on
// But, we need the "id" of the <li> element which is the parent of the <button> element that we clicked on.
// The 'target' property has a propery called 'parentNode' that we can use.
// So, when you click the button => event.target.parentNode.id = theidoftheparent<li>element which is what we want.
// Also, check that you actually clicked on the button and not any other part of the <ul>
// Then, add the parentNode.id to it and call the appropriate function.
var todosUl = document.querySelector('ul');
todosUl.addEventListener('click', function(event){
  var elementClicked = event.target;
  if (elementClicked.className === 'deleteButton'){
    handlers.deleteTodo(elementClicked.parentNode.id);
  } 
  
// To get the 'button' out of the objext
this.createDeleteButton().outerHTML