I know that I can use nodeValue to change the text inside the text likeelement.firstChild.nodeValue = text
but can I use setAttribute to do the same thing?
HTML :
<p id="description">Some text here.</p>
JS :
var description = document.getElementById("description");
description.setAttribute(nodeValue, text);
It doesn't work. Does it means that "nodeValue" is not an attribute of an element?
No. setAttribute
does, well, set an attribute. It doesn't set contents.
However, you can use CSS to display an attribute as if it were content.
var description = document.getElementById("description");
description.setAttribute('data-content', 'Updated text');
#description::after {
content: attr(data-content);
}
<p id="description" data-content="Some text here."></p>
This should only be used for styling purposes, not to insert real content.
You want to set node content here and not node attribute so you could use .textContent
instead :
// Set the text content:
description.textContent = text;
Hope this helps.
var description = document.getElementById("description");
var text = 'New text';
description.textContent = text;
<p id="description">Some text here.</p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With