Superwhiskers Superwhiskers - 3 months ago 9
jQuery Question

Why is it that JQuery and the Javascript DOM methods strip whitespace?

I'm trying to write a chatroom in Javascript. It seems as if you send

h e l l o
in the message submission box, it places
h e l l o
in the message log on everybody's message log. I have also tried to use the native DOM methods, and the same thing happens there too.

The Javascript to place the message in the log is like this:

socket.on('chat message', function(msg){
$('#messages').append($('<li style="background: #ffffff;">' + msg + '</li>'))
})


The HTML of where it would be placed is like this:

<ul id="messages">
</ul>


Can somebody please tell me why this happens, and how I could keep this from happening.

Answer

Browsers don't always display breaking whitespace when showing text, you can change that with CSS

#messages li {
  white-space: pre;
}

The valid values are as follows

Value    |  Description
_________|_________________________________________________________________________
normal   |  Sequences of whitespace will collapse into a single whitespace. 
         |  Text will wrap when necessary. This is default.
_________|_________________________________________________________________________
nowrap   |  Sequences of whitespace will collapse into a single whitespace. 
         |  Text will never wrap to the next line. 
         |  The text continues on the same line until a <br> tag is encountered.
_________|_________________________________________________________________________
pre      |  Whitespace is preserved by the browser. 
         |  Text will only wrap on line breaks.  
         |  Acts like the <pre> tag in HTML.
_________|_________________________________________________________________________
pre-line |  Sequences of whitespace will collapse into a single whitespace.
         |  Text will wrap when necessary, and on line breaks.
_________|_________________________________________________________________________
pre-wrap |  Whitespace is preserved by the browser. 
         |  Text will wrap when necessary, and on line breaks.
_________|_________________________________________________________________________
initial  |  Sets this property to its default value.
_________|_________________________________________________________________________
inherit  |  Inherits this property from its parent element.
_________|_________________________________________________________________________

var msg = "h  e  l  l  o";

$('#messages').append($('<li style="background: #ffffff;">' + msg + '</li>'));
$('#messages2').append($('<li style="background: #ffffff;">' + msg + '</li>'));
#messages li {
  white-space: pre
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="messages"><li>With white-space</li></ul>
<ul id="messages2"><li>Without white-space</li></ul>