Reputation: 6318
Ok so this is my dumb problem. im here learning and...ive been looking at this for a while and i dont understand. i have an array with some values that are fed via an object. like so:
function blogObj(name,date,user_entry){
this.names = name;
this.dates = date;
this.blog_entry = user_entry;
this.propsComb = this.names + this.dates + this.blog_entry;
}
var blogRun = [
new blogObj("name ", "something ", "something "),
new blogObj("name ", "something ", "something "),
new blogObj("name ", "something ", "something "),
new blogObj("name ", "something ", "something "),
new blogObj("name ", "something ", "something "),
];
var i=0;
var mssgs = "";
now when i loop through it like this with this doc.write to test:
function hmm(){
while(i < blogRun.length){
mssgs = blogRun[i].propsComb + '<br/>';
document.write(mssgs);
i++;
}
}
i get all the values i need which are name something something x5 as per the loop and the values of the array. so essentially it works.
now when i replace the "document.write(mssgs)"
with
document.getElementById('showMore').innerHTML = mssgs;
making it this
function hmm(){
while(i < blogRun.length){
mssgs = blogRun[i].propsComb + '<br/>';
//document.write(mssgs);
document.getElementById('showMore').innerHTML = mssgs;
i++;
}
}
it only shows me the last value of the array. it doesnt loop for the rest of the arrays values. all im doing is replacing the .write with getElementById etc..
Upvotes: 2
Views: 4899
Reputation: 62392
At each iteration you are overwriting (re-assigning) the innerHtml
value of 'showMore'
use +=
instead to append (add to) the currently existing contents of 'showMore'
document.getElementById('showMore').innerHTML += mssgs;
Side Note
I would also prefer that you use a for
loop in this situation as you are looping over a static array where the amount of times you need to iterate is known from the beginning
( blogRun.length
)
for ( var i = 0, len = blogRun.length; i < len; i++ ) {
// .... do your stuff here.
}
Upvotes: 6
Reputation: 3532
innerHTML replaces the full content of your element.
this should work better
//before the while loop
var strHTML= '';
...
//inside while loop
strHTML += mssgs;
...
//after while loop
document.getElementById('showMore').innerHTML = strHTML;
Upvotes: 3
Reputation: 8393
.innerHtml will replace the value within the element showMore on each loop. If you want showMore to display all of the values you need to append / concatenate the values together and then replace innerHtml.
Or you should be able to simply append the mssgs value to the innerHtml:
document.getElementById('showMore').innerHTML += mssgs;
Upvotes: 2