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:
- JK Rowling: Harry Potter
- Suzanne Collins: Hunger Games
- J. R. R. Tolkien: Lord of the Rings
- George R.R. Martin: Game of Thrones
- Rick Riordan: Percy Jackson
Using vanilla JS
2
Answers
You should use
createElement
to create a<strong>
tag in which you placeitem.author
.Then make a new text node for the
item.name
usingdocument.createTextNode
Then append the textNode to the
li
and append that to theul
:To create your desired unordered list update the js as follows:
In the modified code, created a
li
element then append it withul
element. If you want the name should be in bold you can use<strong>
or<b>