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
Author by
frequent
Updated on February 25, 2021Comments
-
frequent about 3 years
I'm generating content dynamically and in some instances, I need to set a
as the only content of a<span>
element.However, the following adds
as text vs adding a empty space:var foo = document.createElement("span") foo = document.createTextNode(" ");
which makes sense, so I'm wondering, how would I add
correctly without (!) usinginnerHTML
Thanks for help!
-
CodeFanatic over 10 yearsCheck out this site for more Information[link] utf8-chartable.de/…
-
Combine over 7 yearstext = text.replace(/\s/g, '\u00A0'); - replaces all spaces with their unicode literal
-
Grant Birchmeier about 7 yearsThis is perfect. It also works in the JQuery
text()
command:link.text("(hide\u00A0info)");
-
Bob about 3 yearsI 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 about 3 yearsI 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.
-
Bob about 3 yearsSo, 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