Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 373
Travis J Avatar asked May 06 '12 22:05

Travis J


People also ask

How do you keep spaces in JavaScript?

var text = text. replace(/\s/g, '&nbsp;'); \s will match any white space character, such as space, tab and new line. If you only want to replace space, use / /g instead.

Does CSS ignore whitespace?

How does CSS process whitespace? Most whitespace characters are ignored, not all of them are. In the earlier example one of the spaces between "Hello" and "World!" still exists when the page is rendered in a browser.

How do you preserve white space in HTML?

The HTML <pre> tag defines preformatted text preserving both whitespace and line breaks in the HTML document. This tag is also commonly referred to as the <pre> element.

How do you put spaces between text in JavaScript?

Use the wordSpacing property in JavaScript to set the spacing between words.


1 Answers

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

You can replace it with the &nbsp; entity:

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

\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.
like image 162
Felix Kling Avatar answered Sep 26 '22 10:09

Felix Kling