'Generating List Items from an Array with Javascript [duplicate]
I am trying to generate a list of names from an Array with this piece of script
const names = ["John", "Hanna", "Luis", "Halley", "Maive"]
const list = document.getElementById('my_list')
names.forEach((name) => {
let li = document.createElement("li")
li.innerHTML = name
list.appendChild(li)
})
and this html
<ul id="my_list"></ul>
but its not working. What am I doing wrong?
Solution 1:[1]
You're code works fine I suggest you a slightly different implementation with just one DOM update
const names = ["John", "Hanna", "Luis", "Halley", "Maive"]
window.onload = () => {
const list = document.getElementById('my_list')
list.innerHTML = names.map(name => `<li>${name}</li>`).join('')
}
<ul id="my_list"></ul>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |