0

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?

  • 2
    Seems to work ok for me - are there any errors in your browser console? Perhaps the error is [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/q/14028959) – Nick Parsons May 06 '22 at 13:06
  • 2
    Absolutely working code. But you should use semicolons to close the statements – grisuu May 06 '22 at 13:06
  • @NickParsons, no there aren't. That is what's worrying me – Kwanele Simelane May 06 '22 at 13:07
  • @KwaneleSimelane are you able to create a [mre] so that we can see the issue for ourselves? You can use a [code snippet](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) to help. If you haven't already, you can use a debugger to step through your code. Also might be worth clearing your browser cache to ensure you're using the correct JS file. – Nick Parsons May 06 '22 at 13:09
  • 2
    Code is good. Run it inside `window.onload = function () { ... }` in a script tag in the head and you should see it. – inorganik May 06 '22 at 13:10
  • Thank you so much @inorganik, it works when I run inside ```window.onload```. – Kwanele Simelane May 06 '22 at 13:37

1 Answers1

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>
R4ncid
  • 6,944
  • 1
  • 4
  • 18