Reputation: 5
// 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
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
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