43

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!

3
  • Why would you not want to use innerHTML? Nov 6, 2013 at 10:55
  • 3
    Try: document.createTextNode("\u00a0"); Nov 6, 2013 at 10:56
  • @David: because I was looking for a way to run this through an existing method without having to add an extra clause to use innerHTML in case I need to add a whitespace.
    – frequent
    Nov 6, 2013 at 11:01

3 Answers 3

103

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

var foo = document.createTextNode("\u00A0");
2
  • 5
    text = text.replace(/\s/g, '\u00A0'); - replaces all spaces with their unicode literal
    – Combine
    Feb 2, 2017 at 12:49
  • This is perfect. It also works in the JQuery text() command: link.text("(hide\u00A0info)"); Apr 11, 2017 at 15:24
16

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

1
4

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

3
  • 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, 2021 at 15:49
  • I believe that the use of .innerHTML is a bad choice for a adding a simple &nbsp; as it is very slow and also may add to security risk; thus my answer should be seen in that context. Feb 25, 2021 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, 2021 at 18:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.