I’m using a For loop to run through an array and return relevant strings. When I use getElementById, I only get the last string, but if I use document.write, everything comes out fine.
var names = ["John","Jamie","Jessica","Judy","Jeffery","Joy"];
for (i=0,tot=names.length; i < tot; i++) {
document.getElementById("namelist").innerHTML = names[i];
}
and the HTML is
<p id="namelist">list of names go here</p>
What I get when I run that is “Joy”. Is it not possible to use getElementById in this case? Is there some other way to get the returned list inside of one element?
I’ve read through some of the other questions and answers on here, but none are exactly what I want
Thanks!
You are setting a value in a loop.
First you set it to John. Then you set it to Jamie (so it is no longer John) and so on.
If you want to append a value then you need to do something like:
(Using the
+=operator would be shorter)If you just want to drop the whole lot in, then there is no need to use a loop: