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?

2

3 Answers 3

4

Convert string to array and iterate?

document.getElementById('block').innerHTML.split('').forEach(function(i){
  console.log(i);
});
<div id="block">Text</div>

Sign up to request clarification or add additional context in comments.

2 Comments

@nickzoum there's a plenty of variants to do this, it's one of them
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
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>

2 Comments

</br> is not a valid tag - if you were to self close it, you need to put the slash on the other side <br/> but html 5 doesn't need the slash at all
@Pete Correct its a typo I will change it . Thanks
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

Comments

Your Answer

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.