K.Wu
K.Wu

Reputation: 5

What`s wrong with nodeValue?

// html
<div>Hello World!</div>

// Javascript
var textNode = div.firstChild;
textNode.nodeValue = "Hello Us";

The sample: sample Why can`t i change the text content?

Upvotes: 0

Views: 44

Answers (2)

Georgggg
Georgggg

Reputation: 564

I would suggest you to include an id attribute to that div since it is very likely you have other divs and that can give you trouble.

// html
<div id="myDivId">Hello World!</div>

// Javascript
var node = document.getElementById("myDivId");
node.textContent = "Hello Us";

if you are using jQuery, easier:

jQuery("#myDivId").html("Hello Us");

Upvotes: 0

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

Your problem was you weren't declaring your div variable. I presume you must have got some error. Just reference the div for which you want to change the nodeValue and everything seems good.. Below, I've referred it with getElementsByTagName, you can use any of other options if required.

// Javascript
var div=document.getElementsByTagName('div')[0];
var textNode = div.firstChild;
textNode.nodeValue = "Hello Us";
console.log(textNode.nodeValue);
<div>Hello World!</div>

Upvotes: 1

Related Questions