Search code examples
javascripthtmlarraysinnerhtmlgetelementbyid

Set innerHTML of a div to = multiple array items using getElementById


I'm trying to finish with the html <div id="animal"> Dog Cat Horse </div> but i can't figure out how to combine multiple array elements into one innerHTML. I'm trying something like this:

var myArray = [
  ['Dog', 'Terrier'],
  ['Cat', 'Tabby'],
  ['Horse', 'Shetland'],
];

for (i = 0; i < myArray.length; i++) {
  document.getElementById('animal').innerHTML = locations[i][0];
};
    <div id="animal"> animal names here </div>


Solution

  • You are replacing the content of your div in each iteration in the loop.

    Ideal way would be to create a string of your data and append that in you div. Instead of accessing the dom in each iteration

    var myArray = [
      ['Dog', 'Terrier'],
      ['Cat', 'Tabby'],
      ['Horse', 'Shetland'],
    ];
    var data = "";
    for (i = 0; i < myArray.length; i++) {
      data += " " +  myArray[i][0];
    };
    
    document.getElementById('animal').innerHTML = data;
    <div id="animal"> animal names here </div>