javascript 如何使用 createTextNode 插入 HTML 实体?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20941956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert HTML entities with createTextNode?
提问by Nik Terentyev
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:
如果我想将一个 ascii 符号表单 js 添加到某个节点?尝试作为TextNode
,但它没有将其解析为代码:
var dropdownTriggerText = document.createTextNode('blabla ∧');
回答by dee-see
You can't create nodes with HTML entities. Your alternatives would be to use unicode values
您不能使用 HTML 实体创建节点。您的替代方案是使用 unicode 值
var dropdownTriggerText = document.createTextNode('blabla \u0026');
or set innerHTML
of the element. You can of course directly input &
...
或innerHTML
元素集。你当然可以直接输入&
...
回答by poke
createTextNode
is supposed to take anytext 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.
createTextNode
应该接受任何文本输入并将其完全插入到 DOM 中。这使得无法插入例如 HTML 元素和 HTML实体。它实际上是一个功能,因此您无需先转义这些。相反,您只需对 DOM 进行操作以插入文本节点。
So, you can actually just use the &
symbol directly:
因此,您实际上可以&
直接使用该符号:
var dropdownTriggerText = document.createTextNode('blabla &');
回答by hellork
I couldn't find an automated way to do this. So I made a function.
我找不到自动执行此操作的方法。所以我做了一个函数。
// render HTML as text for inserting into text nodes
function renderHTML(txt) {
var tmpDiv = document.createElement("div"); tmpDiv.innerHTML = txt;
return tmpDiv.innerText || tmpDiv.textContent || txt;
}