Reputation: 1554
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
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
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
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