Laiqa Mohid
Laiqa Mohid

Reputation: 561

how to add words from array to div's inner HTML one at a time?

I was wondering how to add all the words from an array to a div's text content - where the words appear one after the other. I have tried the method below - but it only prints the very last word of the array and nothing else. The word is suppose to fit a thin vertical div. I'm, guessing it's overriding the other words. I'm new to javascript, how would I do this? enter image description here

let sentiment = bgpage.wordObj.wordArr; // array


let divText = document.querySelector('.vertcol1 p')

sentiment.forEach(word => {
   // setInterval
   divText.innerHTML = word
   console.log(word)
})

Upvotes: 0

Views: 181

Answers (1)

Tomas Mudano
Tomas Mudano

Reputation: 44

As it has been said, the problem is that your code is overwriting your div's innerHTML. Think of it this way: by saying divText.innerHTML = word you are tellin each time to the program: "set the whole ineerHTML to this new word", which will leave you at the end with just the last word. You should instead append this new word to whatever is inside of the div. That is done with the +=. Note the difference: = -> assigns a value, += -> appends. Finally, your code would look like this:

let sentiment = bgpage.wordObj.wordArr; // array


let divText = document.querySelector('.vertcol1 p')

sentiment.forEach(word => {
   // setInterval
   divText.innerHTML += word
   console.log(word)
})

Upvotes: 1

Related Questions