Replace paragraph in HTML with new paragraph using Javascript

4k views Asked by At

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;
};
2

There are 2 answers

0
Purag On BEST ANSWER

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.

0
AudioBubble On

You cannot replace nodes into document directly, you may try innerHTML instead:

document.onload = function () {
  document.getElementById("two").innerHTML = "I am the superior text";
};