I am attempting to replace a p
in my HTML doc with a paragraph created in Javascript. Once the page loads, two
will be replaced with t
.
var two = document.getElementById("two");
document.onload = function myFunction() {
var p = document.createElement("p");
var t = document.createTextNode("I am the superior text");
p.appendChild(t);
document.getElementById("p");
document.two = p;
};
You can just replace the text content of the #two
element:
var two = document.getElementById("two"); window.onload = function () { var t = "I am the superior text"; two.textContent = t; };
<p id="two">Lorem ipsum dolor sit amet.</p>
If you use createTextNode
, then you'll need to use two.textContent = t.textContent
to get the actual contents of the textNode object.
Note that you can't replace an existing node in the DOM by straight assignment; that's what you were trying to do.
You cannot replace nodes into document directly, you may try innerHTML instead:
document.onload = function () {
document.getElementById("two").innerHTML = "I am the superior text";
};
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.