Jayleaf
Jayleaf

Reputation: 51

Writing line breaks to a <span> element using JavaScript?

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.

Upvotes: 0

Views: 2756

Answers (3)

Juliano Soder
Juliano Soder

Reputation: 9

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 :)

Upvotes: 0

timolawl
timolawl

Reputation: 5564

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>

Upvotes: 3

freefaller
freefaller

Reputation: 19953

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;

Upvotes: 0

Related Questions