How to add whitespace to DOM in Javascript
21 April 2020
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\xA0Unicode 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.