Home > Back-end >  Setting text of element with JS ignores \n linebreak?
Setting text of element with JS ignores \n linebreak?

Time:11-29

I want to set a the text of a paragraph element via JS. The string contains line breaks (\n), but they are not visible in the paragraph.

This is the desired result:

<p>
  Lorem ipsum dolor sit amet,<br> 
  consetetur sadipscing elitr,<br> 
  sed diam nonumy <br> eirmod tempor...
</p>

This it how it looks when I set the text via JS:

document.getElementById("text").textContent = 
"Lorem ipsum dolor sit amet,\n"   
"consetetur sadipscing elitr,\n"   
"sed diam nonumy \n eirmod tempor...";
<p id="text"></p>

How can I achieve the behaviour of the first example with JS?

CodePudding user response:

From the MDN documentation for HTMLElement.innerText:

Note: innerText is easily confused with Node.textContent, but there are important differences between the two. Basically, innerText is aware of the rendered appearance of text, while textContent is not.

So, if you use innerText instead, you'll get the expected result:

document.getElementById("text").innerText = 
"Lorem ipsum dolor sit amet,\n"   
"consetetur sadipscing elitr,\n"   
"sed diam nonumy \n eirmod tempor...";
<p id="text"></p>

Don't reach for innerText all the time: textContent is more performant... but in some cases like this, innerText is the right tool.

CodePudding user response:

You can try this too. Using insertAdjacentHTML

let innerElem = 
` Lorem ipsum dolor sit amet,<br> 
  consetetur sadipscing elitr,<br> 
  sed diam nonumy <br> eirmod tempor...`;
      
document.getElementById("text").insertAdjacentHTML("afterbegin",innerElem);
<p id="text"></p>

  • Related