0

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?

asked Dec 12, 2018 at 16:51
1
  • Please provide your HTML. Commented Dec 12, 2018 at 16:53

5 Answers 5

1

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

0

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

0

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

0

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

0
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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.