Stefan Falk
Stefan Falk

Reputation: 25397

Why am I not able to insert text nodes which only have zero width whitespaces set?

I am trying to insert whitespace text nodes using JS but it's simply not working. Is the innerHtml property getting ignored for a TextNode?

See my JSFiddle

insertWhitespace = function() {

  var contentEditable = document.getElementById("txt");
  var element = document.getElementById("annyoing-html");

  var textNodeLeft = document.createTextNode("");
  var textNodeRight = document.createTextNode("");

  textNodeLeft.innerHtml = "​";  
  textNodeRight.innerHtml = "​";

  contentEditable.insertBefore(textNodeLeft, element);

  if(element.nextSibling != null) {     
    contentEditable.insertBefore(textNodeRight, element.nextSibling);  
  } else {
    element.appendChild(textNodeRight);
  }
};

I actually plan to insert zero whitespace characters but it's not working like this anyway.

How can I insert such text nodes?

Upvotes: 1

Views: 2210

Answers (4)

Alnitak
Alnitak

Reputation: 339816

Text nodes do not have a .innerHTML property (nb: note the case)

The simplest solution is to simply specify the right content as Unicode literals when you create the elements:

var textNodeLeft = document.createTextNode("\u200b");
var textNodeRight = document.createTextNode("\u200b");

Upvotes: 1

Leon Adler
Leon Adler

Reputation: 3341

As has been stated before,   is a HTML entity. You are trying to fill a text node, not HTML.

Therefore, to fill a "non-breaking whitespace" ( ) into a text node, you can use its unicode character code:

var textNode = document.createTextNode("\xA0");
// or
var textNode2 = document.createTextNode("");
textNode2.data = "\xA0";   // or
textNode2.textContent = "\xA0";

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

HTML entities (&entity;-formatted strings) are, shockingly, for HTML.

For JavaScript, you need to use JavaScript escape sequences.

In this case, non-breaking space, which is \xA0

However, it is very bad practice to chain NBSPs together to artificially create space. You should be using margins, padding, positioning... ANYTHING, so long as it's CSS. Spacing is part of presentation, and presentation is the job of CSS.

For completeness, you can use normal spaces (" ") provided you set the container's CSS to include white-space: pre-wrap to make the whitespace significant.

Upvotes: 2

Ozrix
Ozrix

Reputation: 3515

Yes, text nodes don't have the .innerHTML property. Only HTMLElements do. So, this will work:

var textNodeLeft = document.createElement("span");
textNodeLeft.innerHTML = "    ";

Upvotes: 0

Related Questions