user1395327
user1395327

Reputation:

getElementById in a For loop

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!

Upvotes: 0

Views: 5290

Answers (5)

mplungjan
mplungjan

Reputation: 177786

document.getElementById("namelist").innerHTML += names[i] + "<br/>" 

is likely what you want

the operator I use is += where

a += b;

is the same as

a = a + b;

A simpler way is

var names = ["John","Jamie","Jessica","Judy","Jeffery","Joy"];
document.getElementById("namelist").innerHTML = names[i].join(", ");

Upvotes: 0

Pranav
Pranav

Reputation: 8871

if you want to print all names then you need to append all names in element's innerHTML.

var names = ["John","Jamie","Jessica","Judy","Jeffery","Joy"];
for (i=0,tot=names.length; i < tot; i++) {
 document.getElementById("namelist").innerHTML += names[i]+"<br/>" ;
}

Upvotes: 0

Rashmi Kant Shrivastwa
Rashmi Kant Shrivastwa

Reputation: 1157

a quick write up replace = with +=

var names = ["John","Jamie","Jessica","Judy","Jeffery","Joy"];
for (i=0,tot=names.length; i < tot; i++) {
 document.getElementById("namelist").innerHTML += names[i];
}

Upvotes: 0

mpm
mpm

Reputation: 20155

var names = ["John","Jamie","Jessica","Judy","Jeffery","Joy"];
for (i=0,tot=names.length; i < tot; i++) {
 document.getElementById("namelist").innerHTML += names[i];
}

+= instead of =

Upvotes: 0

Quentin
Quentin

Reputation: 943214

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:

document.getElementById("namelist").innerHTML = document.getElementById("namelist").innerHTML + names[i];

(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:

document.getElementById("namelist").innerHTML = names.join(' ');

Upvotes: 2

Related Questions