How to add whitespace to DOM in Javascript

Sometimes we need to add dynamic content dynamically to the DOM. In these situations, it is common to set whitespace inside some of the elements. So, how can you add white to the DOM in JavaScript?

The best way to add white space to use a unicode literal for a non-breaking space. Instead of specifying non-breaking space with    we can instead use \xC2\xA0.

This ensures that the non-breaking space is evaluated correctly when the markup is being rendered.

So a blank string:

' '

Is usually replace with:

 

However, this won’t get rendered using document.write so in that situation replace   with:

\xC2\xA0

Unicode literals

For other space-related Unicode literals there a multitude of options:

  • \x20 – standard space or \s
  • \xC2\xA0 – non-breaking space or  
  • \x0D – return or \r
  • \x0A –  a newline or \n
  • \x09 – a tab or \t

And there you have it, there’s is a strange amount of depth to for creating whitespace.

Proudly published with Gatsby