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 want to print all data in printarray which is a <p>
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 want to print all data in printarray which is a <p>
-
1
Use
document.getElementById("printarray").innerHTML += array[i]
- when just using=
you are overwriting the existing data on each iteration. – abagshaw Commented Aug 27, 2017 at 23:01 -
no need for loop .. just
document.getElementById("printarray").innerHTML = array.join('')
– Slai Commented Aug 28, 2017 at 0:51
2 Answers
Reset to default 3The 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];
}
You need to use +=
to append the new data to innerHTML
rather than overwriting it each time as you are currently doing with =
.
var array = ["text1", "text2"];
for(var i = 0; i < array.length; i++) {
document.getElementById("printarray").innerHTML += array[i];
}
You can also add a line break with <br>
to put each element on a new line to make things more readable.
var array = ["text1", "text2"];
for(var i = 0; i < array.length; i++) {
document.getElementById("printarray").innerHTML += array[i] + "<br>";
}