我使用普通的js来改变标签元素的内部文本,我不确定我应该使用innerHTML还是nodeValue或textContent。我不需要创建新节点或更改HTML元素或任何东西 - 只需替换文本即可。下面的代码示例:nodeValue vs innerHTML和textContent。如何选择?
var myLabel = document.getElementById("#someLabel");
myLabel.innerHTML = "Some new label text!"; // this works
myLabel.firstChild.nodeValue = "Some new label text!"; // this also works.
myLabel.textContent = "Some new label text!"; // this also works.
我通过jQuery的来源看,它使用的nodeValue只有一个时间,但innerHTML的和的textContent几次。然后我发现这个jsperf测试表明firstChild.nodeValue显着更快。至少这就是我所理解的意思。
如果firstChild.nodeValue快得多,那有什么用?它是否得到广泛支持?还有其他问题吗?
您能否添加摘要?有时链接会被破坏,有时会导致更多的信息而不是相关的信息。 – Panzercrisis
呃,'nodeValue'不能解析HTML – Bergi
“使用textContent可以防止XSS攻击”https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent – DRP