Mario Parra
Mario Parra

Reputation: 1554

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!

Upvotes: 1

Views: 146

Answers (3)

user4573148
user4573148

Reputation:

Here is your code to help append an element to your dom.

http://codepen.io/xequence/pen/ZWPKOW

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

  paragraph.appendChild(text);

  paragraph.className = "heading";
  paragraph.style.width = "100vw";
  paragraph.style.background = "blue";
  var currentDiv = document.getElementById("container");
  document.body.insertBefore(paragraph, currentDiv);
}

Upvotes: 0

Md Mahfuzur Rahman
Md Mahfuzur Rahman

Reputation: 2359

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

Upvotes: 1

Ramin
Ramin

Reputation: 207

Use this

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

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

Upvotes: 0

Related Questions