我有一个创建某些DOM节点的JavaScript函数:如何风格的CSS与JavaScript函数创建DOM元素
function setHeader(){
var questionBox = document.createElement("div");
questionBox.setAttribute("id","question" + (questionNumber + 1));
document.body.insertBefore(questionBox,scriptBox);
var questionElement = document.createElement("h3");
// questionElement.setAttribute("id","question" + (questionNumber + 1));
var questionText = document.createTextNode(questions[questionNumber].question);
questionElement.appendChild(questionText);
questionBox.appendChild(questionElement);
$(questionBox).hide().fadeIn(1000);
}
此功能将创建下列HTML:
<div id="questionHolder">
<h3 id="question">Is the sky blue?</h3>
</div>
我想知道的是,我怎么能使用CSS样式的div
或h3
元素?
我认为CSS文件是在创建DOM节点之前读取的,因为CSS在页眉中链接并且我的JavaScript文件在我的页面的body
标记的末尾被链接。
我认为这意味着CSS样式不会应用到创建的元素,我的测试已经同意这一点。
感谢,感谢任何帮助。
编辑:
我的问题,改变了功能,使它更容易阅读。实际功能将问题从数组中拉出来:
function setHeader(){
var questionBox = document.createElement("div");
questionBox.setAttribute("id","question" + (questionNumber + 1));
document.body.appendChild(questionBox);
var questionElement = document.createElement("h3");
questionElement.setAttribute(questions[questionNumber].question));
var questionText = document.createTextNode("Is the sky blue?");
questionElement.appendChild(questionText);
questionBox.appendChild(questionElement);
}
这似乎不适合我。这会改变什么吗?
我曾尝试它。它没有工作?坚持也许我有一个错误的地方 – Kane
作为@AlienArrays写道,它应该为你工作。 的jsfiddle例如:http://jsfiddle.net/6vSE8/ – Avisho
好,我看到的作品,是否有所作为,如果我拉出来的问题的阵列?我将编辑我的问题 – Kane