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 (!) using innerHTML
Thanks for help!
To add real spaces to your text, you can use the character entity. Tip: The non-breaking hyphen (‑) is used to define a hyphen character (‑) that does not break into a new line.
Use It is the entity used to represent a non-breaking space.
var text = text. replace(/\s/g, ' '); \s will match any white space character, such as space, tab and new line. If you only want to replace space, use / /g instead.
You can use a unicode literal for a non breaking space:
var foo = document.createTextNode("\u00A0");
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With