Felix Felix - 2 months ago 19
Javascript Question

How to get all values from a javascript array and print in a paragraph tag

Please any assistance will be highly appreciated

var array = ["text1","text2"];
for(var i= 0; i< array.length; i++){
document.getElementById("printarray").innerHTML = array[i]; // line 1
Console.log(array[i]); // line 2
}


Line 1 prints only the last text in the array.
Line 2 prints all texts
Why is this so cause I wanna print all data in printarray which is a

Answer Source

The way you were doing it, the innerHTML gets re-written to contain only one array element every time the loop runs.

You could build up a string that contains all of the values within the array, and then set the innerHTML to that string. This would override whatever was in that HTML element - replacing it with all of the elements in the array.

var array = ["text1","text2"];
var temp = "";
for(var i= 0; i< array.length; i++){
   temp += array[i];
}
document.getElementById("printarray").innerHTML = temp;

Alternatively, you can ADD each string to the innerHTML, which would concatenate every string in array onto whatever is already in the HTML element.

var array = ["text1","text2"];
for(var i= 0; i< array.length; i++){
   document.getElementById("printarray").innerHTML += array[i];
}