mh108
2/28/2019 - 8:36 PM

add-remove-DOM.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Lab Week 8</title>
</head>

<body>
  <h2>Favorite Coffee Drinks</h2>
  <p>Enter a Coffee Drink:
    <input type="text" id="inBox">
  </p>
  <p>
    <button id="btn1">Add Ordered List</button> &nbsp;
    <button id="btn2">Add List Item.</button>
  </p>
  <div></div>
  <script src="lab-week-8.js"></script>
</body>

</html>
// jshint esversion: 6

//define the event handler
let main = function() {
  //always declare variables at the top of the function
  let olElement, div, liElement, coffeeDrink;

  //dispatch on button id
  if (this.id == "btn1") {
    //create a new ol element
    olElement = document.createElement("ol");
    //select the empty div on the web page
    div = document.querySelector("div");
    //add the ol element to the div
    //it's not visible on the web page-- use the DevTools Inspector
    div.appendChild(olElement);
  } else if (this.id == "btn2") {
    //create a new li element
    liElement = document.createElement("li");
    //get the content entered by the user
    coffeeDrink = document.querySelector("#inBox").value;
    console.log(coffeeDrink);
    //add the content to the li
    liElement.textContent = coffeeDrink;
    //select the ol element
    olElement = document.querySelector("ol");
    //append the li element to the ol
    //this you can see in the browser
    olElement.appendChild(liElement);
  } else if (this.id == "btn2") {
    //handle the Remove List Item button
    //...
  }
};

//register event handler
window.addEventListener("load", function() {
  let buttons = document.querySelectorAll("button");
  for (var i = 0; i < buttons.length; ++i)
    //when the button gets clicked, who ya gonna call?
    buttons[i].addEventListener("click", main);
});