Abhijeet Dolai
Abhijeet Dolai

Reputation: 31

Why does the innerHTML property automatically trims the string?

here is my code:

    function myFunction() {
    var str = "  Hello World  ";
	document.getElementById("demo").innerHTML=str;
    alert(str);
    }
    <p id="demo"></p>
    <button onclick="myFunction()">Try it</button>

While the Alert window outputs the string as it is i.e with spaces, the p element receives the string in trimmed form i.e with no spaces?

Upvotes: 3

Views: 1404

Answers (4)

davidxxx
davidxxx

Reputation: 131496

In HTML, regular whitespace chararacters between tags are not interpreted as whitespaces to render by the browser.
Declaring one or multiple of them will give the same result: they are collapsed and are rendered as a single space.

To render multiple whitespaces, you have two ways :

  • in plain HTML use the &nbsp; entity ( , or non-breaking space)

  • in CSS, use the white-space property: white-space: pre-wrap;

pre-wrap

Sequences of whitespace are preserved. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.

Source: MDN’s article on white-space

Upvotes: 3

Stephan
Stephan

Reputation: 2115

If you would like to see those whitespaces, you could use CSS's white-space property and set it to pre (which breaks only on given line-breaks) or pre-wrap (which breaks whenever necessary).

However are you sure, that you really want to do positioning of text in HTML? Is there any reason that you leave the spaces and instead use padding on your element to shift its content?

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 122006

It is not the innerHTML. Real culprit is Browser. You cannot see the spaces in the browser directly with string literals as all browsers will always truncate spaces in HTML. You have use &nbsp to see them.

While browser processing your html, it follows some rules.

Here is the 16.6.1 The 'white-space' processing model

If 'white-space' is set to 'normal', 'nowrap', or 'pre-line',

every tab (U+0009) is converted to a space (U+0020)

any space (U+0020) following another space (U+0020) — even a space before the inline, if that space also has 'white-space' set to 'normal', 'nowrap' or 'pre-line' — is removed.

Upvotes: 2

ptts
ptts

Reputation: 1053

It depends on the browser.

If you wanna be sure to have the space, do this:

function myFunction() {
var str = "  Hello World  ";
document.getElementById("demo").innerHTML="&nbsp" + str + "&nbsp";
alert(str);
}
myFunction();

Upvotes: 0

Related Questions