我可以使用 setAttribute 来更改文本节点内的文本吗?

fun*_*fun 5 javascript

我知道我可以使用 nodeValue 来更改文本中的文本,
element.firstChild.nodeValue = text
但我可以使用 setAttribute 来做同样的事情吗?

HTML :

<p id="description">Some text here.</p>
Run Code Online (Sandbox Code Playgroud)

JS:

var description = document.getElementById("description");
description.setAttribute(nodeValue, text);
Run Code Online (Sandbox Code Playgroud)

它不起作用。这是否意味着“nodeValue”不是元素的属性?

Ori*_*iol 4

setAttribute,确实设置了一个属性。它不设置内容。

但是,您可以使用 CSS 来显示属性,就好像它是内容一样。

var description = document.getElementById("description");
description.setAttribute('data-content', 'Updated text');
Run Code Online (Sandbox Code Playgroud)
#description::after {
  content: attr(data-content);
}
Run Code Online (Sandbox Code Playgroud)
<p id="description" data-content="Some text here."></p>
Run Code Online (Sandbox Code Playgroud)

这应该仅用于样式目的,而不是插入真实内容。