// html
<div>Hello World!</div>
// Javascript
var textNode = div.firstChild;
textNode.nodeValue = "Hello Us";
The sample: sample Why can`ti change the text content?
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>
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.