0

Hi let's assume that I have the following code:

var information_paragraph = document.getElementById(myDivElement);
var infoText = "Hello World!";
information_paragraph.innerHTML = infoText;

So instead of adding the whole string "Hello World!", I was thinking if I can add a char of that string one at a time. How to access the characters of the string and create a for loop to add content in the innerHTML rather than replacing it?

Loizos Vasileiou
  • 674
  • 10
  • 37
  • Possible duplicate of [How can I process each letter of text using Javascript?](https://stackoverflow.com/questions/1966476/how-can-i-process-each-letter-of-text-using-javascript) and [Appending using native javascript](https://stackoverflow.com/questions/42517697/appending-html-using-native-javascript) – Pete Mar 19 '19 at 11:27
  • `for(var char of text)`? – nick zoum Mar 19 '19 at 11:56

3 Answers3

4

Convert string to array and iterate?

document.getElementById('block').innerHTML.split('').forEach(function(i){
  console.log(i);
});
<div id="block">Text</div>
  • @nickzoum there's a plenty of variants to do this, it's one of them –  Mar 19 '19 at 11:30
  • You don't seem to have fully answered the question: *How to access the characters of the string and create a for loop to add content in the innerHTML rather than replacing it* – Pete Mar 19 '19 at 11:36
1

I think what you want is to use the string as array and append it to the inner html if you ant it all in a sane line remove "</br>"+

var information_paragraph = document.getElementById("myDivElement");
var infoText = "Hello World!";
for(i = 0; i < infoText.length; i++)
information_paragraph.innerHTML += "<br/>"+infoText[i];
<div id="myDivElement">
</div>
Andam
  • 2,087
  • 1
  • 8
  • 21
  • `` is not a valid tag - if you were to self close it, you need to put the slash on the other side `
    ` but html 5 doesn't need the slash at all
    – Pete Mar 19 '19 at 11:33
  • @Pete Correct its a typo I will change it . Thanks – Andam Mar 19 '19 at 11:35
0

I think may this work

const  information_paragraph = 
document.getElementById('myDivElement');
let  infoText = "Hello World!"; 
let infoTextLetters ;
for(i in infoText){
  infoTextLetters +=  `
   <br> ${infoText[i]} ` ;

information_paragraph.innerHTML = infoTextLetters
Akram Elhaddad
  • 194
  • 3
  • 7