Why does the innerHTML property automatically trim 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>
      

Run codeHide result


While the Alert window displays the string as it is ie with spaces, does the p element take a truncated ie without spaces?

+3


source to share


4 answers


It's not innerHTML. The real culprit is the browser. You cannot see whitespace in the browser directly with string literals, since all browsers will always truncate whitespace in HTML. You can use &nbsp

to see them.

While the browser is processing your html, it follows some rules.



Here is 16.6.1 White Space Processing Model

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

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

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

+2


source


In HTML, regular space characters between tags are not interpreted as spaces for rendering by the browser.
Declaring one or more of these will give the same result: they are reset and displayed as a single space.

To make multiple spaces, you can do two ways:

  • in normal HTML use an object &nbsp;

    (  

    or non-breaking space)

  • in CSS, use the property white-space

    :white-space: pre-wrap;



pre-wrap

Sequences of spaces are retained. The lines are split into a new character line <br>

and, if necessary, to fill the lines.

Source: MDN article atwhite-space

+2


source


If you want to see those whitespace, you can use the CSS pre white-space property (which only breaks on given line breaks) or pre-wrap

(which breaks when needed).

However, are you sure you really want to position the text in HTML? Is there a reason why you leave whitespace and instead use padding

for your element to offset its content?

+1


source


It depends on the browser.

If you want to have free space, do the following:

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

      

-1


source







All Articles