I would like to display an array into html under eachother.
Example:
let cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
What I get is: Saab,Volvo,BMW
What I want is:
Saab
Volvo
BMW
Can someone help me with this one?
-
Please provide your HTML.natn2323– natn23232018年12月12日 16:53:35 +00:00Commented Dec 12, 2018 at 16:53
5 Answers 5
join
the array with a br
element. Here I've used insertAdjacentHTML
...
let cars = ["Saab", "Volvo", "BMW"];
document.body.insertAdjacentHTML('beforeend', cars.join('<br/>'));
...but innerHTML
would work too.
let cars = ["Saab", "Volvo", "BMW"];
document.body.innerHTML = cars.join('<br/>');
answered Dec 12, 2018 at 17:01
Sign up to request clarification or add additional context in comments.
Comments
Here is a quick hacky solution :)
let cars = ["Saab", "Volvo", "BMW"];
for(var i = 0; i < cars.length; i++)
{
document.body.innerHTML += '<div >' + cars[i] + '</div>';
}
<body>
</body>
answered Dec 12, 2018 at 16:54
Comments
const cars = ["Saab", "Volvo", "BMW"];
const list = document.getElementById("demo");
cars.forEach(car => {
let item = document.createElement("li");
item.innerText = car;
list.appendChild(item);
})
<ul id="demo"></ul>
answered Dec 12, 2018 at 16:55
Comments
Use forEach to loop through cars array and using br tag on every append to existing content of demo element
let cars = ["Saab", "Volvo", "BMW"];
cars.forEach(v => {
document.getElementById("demo").innerHTML += v + '<br />';
})
codepen - https://codepen.io/nagasai/pen/MZabXm
let cars = ["Saab", "Volvo", "BMW"];
cars.forEach(v => {
document.getElementById("demo").innerHTML += v + '<br />';
})
<div id="demo"></div>
answered Dec 12, 2018 at 16:56
Comments
var cars = ["Saab", "Volvo", "BMW"];
var content = '';
for(var i=0; i<cars.length; i++){
content+= "<div>"+cars[i]+"</div>";
}
document.getElementById("demo").innerHTML = content;
answered Dec 12, 2018 at 16:59
Comments
lang-js