Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use setAttribute to change the text inside the text node?

Tags:

javascript

I know that I can use nodeValue to change the text inside the text like
element.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?

like image 601
fun Avatar asked Sep 13 '16 15:09

fun


2 Answers

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.

like image 85
Oriol Avatar answered Nov 14 '22 23:11

Oriol


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>
like image 27
Zakaria Acharki Avatar answered Nov 14 '22 23:11

Zakaria Acharki