javascriptlistfor-loopappendchildcreateelement

Create Unordered List from Object of arrays


I want to create an unordered list using vanilla JS to create a list from an array of objects. Not sure how to do that.

This is my current code:

let myObj = [
  {name: "Harry Potter", author: "JK Rowling"},
  {name: "Hunger Games", author: "Suzanne Collins"},
  {name: "Lord of the Rings", author: "J. R. R. Tolkien"},
  {name: "Game of Thrones", author: "George R.R. Martin"},
  {name: "Percy Jackson", author: "Rick Riordan"},
];

console.log(myObj);

let myUL = document.createElement("UL");
myUL.setAttribute("id", "myUL");
document.getElementById("myDiv").appendChild(myUL);
for (const item of myObj) {
   document
   .getElementById("myUL")
   .appendChild(document.createElement("LI"));
}
<div id="myDiv"></div>

Not sure how to make my list look like:

Using vanilla JS


Solution

  • You should use createElement to create a <strong> tag in which you place item.author.

    Then make a new text node for the item.name using document.createTextNode

    Then append the textNode to the li and append that to the ul:

    const myObj = [
      {name: "Harry Potter", author: "JK Rowling"},
      {name: "Hunger Games", author: "Suzanne Collins"},
      {name: "Lord of the Rings", author: "J. R. R. Tolkien"},
      {name: "Game of Thrones", author: "George R.R. Martin"},
      {name: "Percy Jackson", author: "Rick Riordan"},
    ];
    
    const myUL = document.createElement("UL");
    myUL.setAttribute("id", "myUL");
    
    const ul = document.getElementById("myDiv").appendChild(myUL);
    
    for (const item of myObj) {
        let author = document.createElement("strong");
        author. textContent = item.author + ': ';
        
        let li = document.createElement("li");    
        li.appendChild(author);
        li.appendChild(document.createTextNode(item.name))
        
        ul.appendChild(li);
    }
    <div id="myDiv"></div>