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

59,108

Solution 1

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

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

Solution 2

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  
  • \x0D – carriage return or \r
  • \x0A – newline or \n
  • \x09 – tab or \t

In your case: \xC2\xA0

Solution 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

Share:
59,108
frequent
Author by

frequent

Updated on February 25, 2021

Comments

  • frequent
    frequent about 3 years

    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!

  • CodeFanatic
    CodeFanatic over 10 years
    Check out this site for more Information[link] utf8-chartable.de/…
  • Combine
    Combine over 7 years
    text = text.replace(/\s/g, '\u00A0'); - replaces all spaces with their unicode literal
  • Grant Birchmeier
    Grant Birchmeier about 7 years
    This is perfect. It also works in the JQuery text() command: link.text("(hide\u00A0info)");
  • Bob
    Bob about 3 years
    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.
  • Admin
    Admin about 3 years
    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.
  • Bob
    Bob about 3 years
    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