41

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!

frequent
  • 27,643
  • 59
  • 181
  • 333

3 Answers3

96

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

var foo = document.createTextNode("\u00A0");
vcsjones
  • 138,677
  • 31
  • 291
  • 286
15

If you don't want to use innerHTML, you can use a hexadecimal escape.

The most common:

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

In your case: \xC2\xA0

neonblitzer
  • 124
  • 1
  • 2
  • 10
CodeFanatic
  • 11,434
  • 1
  • 20
  • 38
  • 1
    Check out this site for more Information[link] http://www.utf8-chartable.de/unicode-utf8-table.pl?start=128&number=128&utf8=string-literal&unicodeinhtml=hex – CodeFanatic Nov 06 '13 at 11:07
3

Append the non breaking space to your parent node, let us refer to it as "parent" below i.e.:

parent.append("\u00A0");

source: https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append

  • 1
    I see you are new to the platform. You should not answer a question unless you have something that was not covered by the existing answers. – Bob Feb 24 '21 at 15:49
  • I believe that the use of .innerHTML is a bad choice for a adding a simple   as it is very slow and also may add to security risk; thus my answer should be seen in that context. – Sinan Gabel Feb 25 '21 at 16:26
  • So, make your point in the answer :) explain why innerHTML is a bad choice, add references, you can create code snippets and you may show that it is slow. And welcome to the comunity – Bob Feb 25 '21 at 18:35