How to dynamically add whitespace in element's text?

12,267

Solution 1

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

a_element.innerHTML = " "

Solution 2

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.

Share:
12,267
evfwcqcg
Author by

evfwcqcg

Updated on July 15, 2022

Comments

  • evfwcqcg
    evfwcqcg almost 2 years

    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?