0

I have data stored in multiple arrays. I want to be able to display the elements in each array on the page using innerHTML. The problem is is that each time through the for-loop the next element in the array overwrites the previous element. How do I display all elements at once without anything being overwritten? Here is my set up:

 for(var item in list){
 document.getElementById('results').innerHTML = "Results: " + item;
 }

So that might display the contents of the first array and then i'd create another loop to display contents of second array, etc. Is there a better way to display the contents of multiple arrays such that nothing overwrites previous content?

kartikmaji
9868 silver badges23 bronze badges
asked Dec 29, 2015 at 0:18
2
  • You could do .innerHTML += 'more results' Commented Dec 29, 2015 at 0:21
  • Also, best not to use for...in loops for arrays. Reserve that loop for objects. Commented Dec 29, 2015 at 0:34

1 Answer 1

1

Edit your code to

for(var item in list){
 document.getElementById('results').innerHTML = "Results: ";
 document.getElementById('results').innerHTML = document.getElementById('results').innerHTML+ item;
 // Or same way to write it
 // document.getElementById('results').innerHTML += item;
}
answered Dec 29, 2015 at 0:23
Sign up to request clarification or add additional context in comments.

1 Comment

This prints the items but it also repeats "Results" in between printed elements.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.