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 ©</div>
<script>
var test = document.getElementById('test');
console.log(test.childNodes[0].nodeValue);
// expected: copyright ©
// actual: copyright ©
</script>
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.
&...;
(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: "©"
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With