0

My goal is to take an array, and write each element onto a HTML page using a <span> element with .textContent using a for loop. Only problem is that instead of:

Error1
Error2

I get:

Error1<br/>Error2<br/>

HTML code:

<p><span id="EBox"></span></p>

JS code:

var EBox = document.getElementById("EBox");
var eArray = []; //Elements get added via push

for (var i = 0; i < eArray.length; i++) {
    EBox.textContent = EBox.textContent + eArray[i] + '<br/>';
}

The entire system works, but it just ends up as one jumbled sentence. What can I change to make it add the line breaks? I've tried '<br>', '<br />' and '\n' with similar results.

2
  • Please show how your eArray elements look like. Commented Apr 29, 2016 at 18:06
  • You can't use .textContent for this, because that's just text without any HTML rendering. Commented Apr 29, 2016 at 18:59

3 Answers 3

3

Use .innerHTML .insertAdjacentHTML instead of .textContent as .textContent does not parse the HTML <br> but simply outputs it as text.

Also if you're appending to the HTML each time, it's better to use .insertAdjacentHTML as it does not reparse the previous HTML, thus making it much faster and less error prone than .innerHTML.

var strArr = ['foo', 'bar'];

strArr.forEach(function(str) {
  document.querySelector('div').insertAdjacentHTML('beforeend', str + '<br>');
});
<div></div>

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

1 Comment

Didn't know about .insertAdjacentHTML - nice call :-)
0

Instead of .textContent use .innerHTML.

I would also recommend building up a string first before using .innerHTML so the DOM isn't rebuilt each time...

var EBox = document.getElementById("EBox");
var eArray = []; //Elements get added via push

var html = "";    
for (var i = 0; i < eArray.length; i++) {
    html += eArray[i] + '<br/>';
}
EBox.innerHTML = html;

Comments

0

I found a better answer here:

https://developer.mozilla.org/pt-BR/docs/Web/CSS/word-break

You can use CSS to do this, see below:

span{word-break: break-word;}

or

span{word-break: break-all;}

BREAKE-WORD will put the next word in a new line and BREAKE-ALL will break the text justifying the content, when it gets bigger than the div or span container.

I hope I'd help :)

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.