evfwcqcg
evfwcqcg

Reputation: 16345

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?

Upvotes: 4

Views: 15543

Answers (3)

Tony Wickham
Tony Wickham

Reputation: 4766

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.

Upvotes: 0

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201658

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 \u00A0 escape in JavaScript:

a_element.innerText = "\u00A0";

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

Upvotes: 12

Sanchit
Sanchit

Reputation: 2260

Use .innerHTML as you need to edit the HTML of that particular link.

a_element.innerHTML = "&nbsp;"

Upvotes: 13

Related Questions