How do I add a non-breaking whitespace in JavaScript without using innerHTML?

frequent picture frequent · Nov 6, 2013 · Viewed 52k times · Source

I'm generating content dynamically and in some instances, I need to set a &nbsp; as the only content of a <span> element.

However, the following adds &nbsp; as text vs adding a empty space:

var foo = document.createElement("span")
foo = document.createTextNode("&nbsp;");

which makes sense, so I'm wondering, how would I add &nbsp; correctly without (!) using innerHTML

Thanks for help!

Answer

vcsjones picture vcsjones · Nov 6, 2013

You can use a unicode literal for a non breaking space:

var foo = document.createTextNode("\u00A0");