Mario Parra Mario Parra - 6 months ago 19
Javascript Question

Creating element with text at the same time

I'm trying to create a paragraph element with some text, but I think I'm appending the text before the paragraph element is added to the DOM. How can I fix this?

function myFn() {
var paragraph = document.createElement("P");
var text = document.createTextNode("This is some paragraph text.");

paragraph.className = "heading";
paragraph.style.width = "100vw";
paragraph.style.background = "blue";
document.getElementById("container").appendChild(paragraph);
document.getElementById("heading").appendChild(text);
}


Pen: http://codepen.io/ourcore/pen/XdGRXN

Thanks!

Answer

Try like this: See DEMO

function myFn() {  
  var paragraph = document.createElement("P");
  var text = document.createTextNode("This is some paragraph text.");

  paragraph.id = "heading";

  paragraph.style.width = "100vw";
  paragraph.style.background = "blue";
  document.getElementById("container").appendChild(paragraph);
  document.getElementById("heading").appendChild(text);
}
Comments