我正在尝试使用一些文本创建一个段落元素,但我想我会在将段落元素添加到DOM之前附加文本。我该如何解决这个问题?
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);
}
笔:http://codepen.io/ourcore/pen/XdGRXN
谢谢!
答案 0 :(得分:1)
尝试这样: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);
}
答案 1 :(得分:0)
使用此
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);
}
答案 2 :(得分:0)
这是您的代码,以帮助将元素附加到您的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);
}