How to preserve whitespace in dynamically added javascript DOM element without using CSS?

20,450

Solution 1

White space characters are usually collapsed in HTML (by default).

You can replace it with the   entity:

var text = text.replace(/\s/g, ' ');

\s will match any white space character, such as space, tab and new line. If you only want to replace space, use / /g instead.

Other options which avoid string manipulation:

  • Put the text in a pre element.
  • Set the CSS 2 white-space property to pre as @Esailija pointed out. You can always add CSS properties dynamically to elements, they don't have to be specified in a style sheet.

Solution 2

use  

zlp.innerHTML = "hello     hello";

Like everyone else just said.

Share:
20,450
Travis J
Author by

Travis J

I really appreciate the Stack Exchange community. This isn't a terrible search . VP of a medium company, B.S. in Computer Science, mostly working with the ASP.NET MVC technology stack. I am the only person at the company who deals with software development making me fill the rolls of a software designer, programmer, dba, server admin, and graphics artist. As you can see from my gravatar, this causes me to wear many hats (hint: they are all from an old winterbash). My main goals when designing and coding are: how can I make the user experience easiest, and how can I reduce redundancy. "Acknowledge your faults so you can overcome them."

Updated on December 26, 2021

Comments

  • Travis J
    Travis J over 2 years

    When adding in text with small whitespace appended to it for alignment purposes the whitespace is trimmed off (the whitespace is added in c# so by the time it gets to front end Javascript it cannot be edited - it would be nice to just use some CSS to do this but it is not an option).

    Here is what I tried so far:

    var zlp = document.getElementById("testDiv")
    zlp.innerHTML = "hello                hello"
    var zzz = document.createTextNode("hello                hello")
    zlp.appendChild(zzz)
    <div id="testDiv"></div>

    Both of which produce hello hello.

  • Esailija
    Esailija about 12 years
    well not always, you can use css like white-space: pre;
  • gotofritz
    gotofritz about 12 years
    as someone said below, OP -> "Css in not an option"
  • gotofritz
    gotofritz about 12 years
    also, strictly speaking \s !== '&nbsp;'. Just for the record.
  • Travis J
    Travis J about 12 years
    @FelixKling - var pr = document.createElement("pre"); pr.innerHTML = "hello hello"; zlp.appendChild(pr); worked. Thanks!
  • mikabytes
    mikabytes over 7 years
    Without CSS there is no way to preserve the exact behavior of normal consecutive spaces. The HTML white space entities such as &nbsp; does not wrap on line-break, which makes them similar but not the same. The other HTML white space entities such as &thinsp;, &ensp; and &emsp; also does not wrap. If CSS was an option, the white-space: pre-line; would be your answer.