I am wanting to create an array of objects and display a specific list of properties when certain conditions are met.
The following code does what I want when I print it to the console or use document.write.
var people = [{
firstName: 'John',
lastName: 'Doe',
age: 23,
},{
firstName: 'Jane',
lastName: 'Doe',
age: 53,
}]
for(i = 0; i < people.length; i++){
if(people[i].age < 65){
document.write(people[i].firstName + ' ' +
people[i].lastName + ' has printed to document. <br>');
}
}
But when I go to run the code in the browser, using document.getElementById, only the last item is displaying.
for(i = 0; i < people.length; i++){
if(people[i].age < 65){
result = 'Only ' + people[i].firstName + ' ' +
people[i].lastName + ' is printed to document. Why?';
}
}
document.getElementById('names').innerHTML = result;
Could someone explain to me why all items appear using document.write?
While only the last item appears when using document.getElementById?