How To Insert Html Entities With Createtextnode?
If I want to add an ascii symbol form js to a node somewhere? Tried as a TextNode, but it didn't parse it as a code: var dropdownTriggerText = document.createTextNode('blabla &
Solution 1:
You can't create nodes with HTML entities. Your alternatives would be to use unicode values
var dropdownTriggerText = document.createTextNode('blabla \u0026');
or set innerHTML
of the element. You can of course directly input &
...
Solution 2:
createTextNode
is supposed to take any text input and insert it into the DOM exactly like it is. This makes it impossible to insert for example HTML elements, and HTML entities. It’s actually a feature, so you don’t need to escape these first. Instead you just operate on the DOM to insert text nodes.
So, you can actually just use the &
symbol directly:
var dropdownTriggerText = document.createTextNode('blabla &');
Solution 3:
I couldn't find an automated way to do this. So I made a function.
// render HTML as text for inserting into text nodesfunctionrenderHTML(txt) {
var tmpDiv = document.createElement("div"); tmpDiv.innerHTML = txt;
return tmpDiv.innerText || tmpDiv.textContent || txt;
}
Post a Comment for "How To Insert Html Entities With Createtextnode?"