'Display the elements of the array one by one in a column js

I have an application where the user selects the words he will save. I write all these words into an array. I need to display each element of this array in a column so that when hovering over you could see the information (or by clicking) I tried to iterate over each element of the array using for and foreach but only the last element was displayed How can I arrange array elements in a column?

Array:

let a = ["First word","Second word","Third word"]

An example of what I need:

  • First word
  • Second word
  • Third word

Need to display it on the page through textContent or innerHTML or something like that.



Solution 1:[1]

What you can do is initializing a list and the adding dynamically all items to that list.

let a = ["First word","Second word","Third word"]

const list = document.getElementById('myList')

a.forEach(elem => {
  const item = document.createElement('li')
  item.textContent = elem // or item.innerHTML
  list.appendChild(item)
})
<ul id="myList"></ul>

Solution 2:[2]

Solution using for in:

let a = ["First word","Second word","Third word"],
  $list = document.querySelector('#list')

for(let i in a) {
  $list.insertAdjacentHTML('beforeend', `<li>${a[i]}</li>`)
}
<ol id="list">List of items
</ol>

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 RenaudC5
Solution 2 NNL993