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.
CodePudding user response:
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>
CodePudding user response:
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>
CodePudding user response:
You didn't show any attempt on looping through that array.
Anyway this is a simple demo appending each array item (word) to the div#container
inside a <ul>
as a <li>
element.
I crafted such logic in a function showListOfWordsFromArray
let words = ["First word","Second word","Third word"];
showListOfWordsFromArray(words);
function showListOfWordsFromArray(words){
let container = document.getElementById('container');
let listOfWords = document.createElement('ul');
for(let item of words){
let listItem = document.createElement('li');
listItem.innerText = item;
listOfWords.appendChild(listItem);
//if just appending text to the container (instead of making an unordered list)
//container.innerText = item "\n";
}
container.appendChild(listOfWords);
}
<div id="container">
</div>