Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

text nodeValue containing HTML entity

Tags:

javascript

I'm creating a real time HTML editor that loads after a DOM has been rendered, and builds the source by looping through all nodes. I've noticed that when I try to read nodeValue of a text node containing an HTML entity, I always get the rendered unicode value of that entity.

How can I read a rendered text node, and keep the HTML entity code? (using vanilla JS)

Example:

<div id="test">copyright &copy;</div>
<script>
var test = document.getElementById('test');
console.log(test.childNodes[0].nodeValue);
// expected: copyright &copy;
// actual: copyright ©
</script>
like image 796
Shea Avatar asked Jul 10 '13 22:07

Shea


1 Answers

Unfortunately you can't. The Text interface inherits from CharacterData, and both interfaces provide only DOMStrings as a return value, which contains Unicode characters.

Furthermore, the HTML5 parsing algorithm basically removes the entity entirely. This is defined in several sections of 8.2.4 Tokenization.

  • 8.2.4.1 Data state: describes that an ampersand puts the parser to the Character reference in data state
  • 8.2.4.2 Character reference in data state describes that the tokens followed by the ampersand should be consumed. If everything works fine, it will return the Unicode character tokens, not the entity!
  • 8.2.4.69 Tokenizing character references describes how one interprets &...; (basically do some things and if everything is OK, look it up in the table).

So by the time your parser has finished the entity is already gone and has been replaced by the Unicode symbols. This is not that surprising, since you can also just put the symbol © right into your HTML code if you want.

However, you can still undo that transformation: you need to take a copy of the table, and check for any character in your document whether it has a entry in it:

var entityTable = {
  169: "&copy;"
}

function reEntity(character){
  var index = character.charCodeAt(0), name;

  if( index < 127) // ignore ASCII symbols
    return character;

  if( entityTable[index] ) {
    name = entityTable[index];
  } else {
    name = "#"+index;
  }
  return "&"+name+";"
}

This is quite a cumbersome task, but due to the parser's behaviour you probably have to do it. (Don't forget to check whether someone has already done that).

like image 61
Zeta Avatar answered Sep 21 '22 12:09

Zeta