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>
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>
Share
Improve this question
asked Jul 10, 2013 at 22:40
SheaShea
1,9502 gold badges18 silver badges42 bronze badges
0
1 Answer
Reset to default 8Unfortunately 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: "©"
}
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).
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744212321a4563392.html
评论列表(0条)