How do I add a non-breaking whitespace in JavaScri

2019-03-18 01:18发布

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!

2条回答
相关推荐>>
2楼-- · 2019-03-18 01:58

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

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-03-18 02:02

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

var foo = document.createTextNode("\u00A0");
查看更多
登录 后发表回答