简体   繁体   中英

How to dynamically add whitespace in element's text?

I want to insert whitespace in DOM element.

For instance, I want to change this

<a></a>

to this

<a> </a>

If I manually add &nbsp to DOM element, then it renders &nbsp as a whitespace. But when I want to add this dynamically, I use innerText ,

 a_element.innertText = "&nbsp"

and as result it doesn't convert &nbsp to whitespace and renders it as a text ( <a>&nbsp</a> ). How can I fix this?

根据需要使用.innerHTML编辑该特定链接的HTML。

a_element.innerHTML = "&nbsp;"

HTML entity references are processed only in HTML parsing. In any case, it is best to put the character directly into the content. If you do not know how to type the no-break space in your authoring environment, you can use the \\xA0 or escape in JavaScript:

a_element.innerText = "\u00A0";

BTW, the no-break space is not a whitespace character by HTML specs.

You can also just copy the whitespace character you want and paste it into your javascript string. For instance, I had a &emsp; in my html; when I loaded the page, I copied that space and pasted it into a string in my javascript:

var myString = "Here is &emsp; --> <--";

Note that it looks like a regular space on here, but it renders into the original whitespace copied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM