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

3

46

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!

Dimitri answered 6/11, 2013 at 10:51 Comment(3)
Why would you not want to use innerHTML?Nathalie
Try: document.createTextNode("\u00a0");Oscular
@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.Dimitri
H
109

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

var foo = document.createTextNode("\u00A0");
Highcolored answered 6/11, 2013 at 10:56 Comment(2)
text = text.replace(/\s/g, '\u00A0'); - replaces all spaces with their unicode literalScreening
This is perfect. It also works in the JQuery text() command: link.text("(hide\u00A0info)");Dielectric
K
18

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

Khoury answered 6/11, 2013 at 10:58 Comment(1)
Check out this site for more Information[link] utf8-chartable.de/…Khoury
I
5

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

Ironsides answered 24/2, 2021 at 14:15 Comment(3)
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.Benefactress
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.Ironsides
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 comunityBenefactress

© 2022 - 2024 — McMap. All rights reserved.