How can we refresh an array displayed in an HTML element after an item is pushed to it?

Viewed 1567

This file is a simple to do list generator. it starts with three sample items being displayed in a div from a JS array. onclick of button one "push" a prompt comes up and whatever the user adds gets added to the array in JS. this works fine as per the console. the second button "shift" pulls the first item off the list (in traditional to do list style) as the user does one item at a time.the push and shift button both run corresponding JS functions which do the work perfectly. in the console the array is updated each time wither is used.

my question: how do i get the div to refresh the array "toDoListJoined" once a modification is made to the array "toDoList" thru the buttons???

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

 <head>
 <meta charset="utf-8" />
 <title>JavaScript To Do List</title>
 </head>


 <body id="home">
   <button id="push" onclick="pushPrompt()">Add something to the end of your list</button>
   <button id="shift" onclick="shiftIt()">Remove the first item from your list</button>


 <p id="listPlace">
 <!--Here's where the magic happens-->
 </p>

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 <script type="text/javascript">
   let toDoList = ["sample item 1", "sample item 2", "sample item 3"];
   let toDoListJoined = toDoList.join("<br>");
   let addItem = "";

document.getElementById("listPlace").innerHTML = toDoListJoined;

function pushPrompt() {
  addItem = prompt("What is the item you want to add to your list?", "Sample item");
  toDoList.push(addItem);
}

function shiftIt() {
  toDoList.shift();
}
 </script>

 </body>

</html>
1 Answers

You can create a new method so that the html is updated:

//create a new method on the Array to push the item and update the HTML. 
toDoList.pushAndUpdate= function(item) {
    //push the item into the array using the prototype push method.
    Array.prototype.push.call(this, item);
    //update the html of my element. 
    document.getElementById("listPlace").innerHTML= this.join("<br>");
}
Related