2014-01-30 63 views
1

我有一个创建某些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样式的divh3元素?

我认为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); 
} 

这似乎不适合我。这会改变什么吗?

+0

我曾尝试它。它没有工作?坚持也许我有一个错误的地方 – Kane

+0

作为@AlienArrays写道,它应该为你工作。 的jsfiddle例如:http://jsfiddle.net/6vSE8/ – Avisho

+0

好,我看到的作品,是否有所作为,如果我拉出来的问题的阵列?我将编辑我的问题 – Kane

回答

1

就在添加样式属性你的脚本,它会为你工作,

questionBox.setAttribute("style",""background-color":"yellow""); 

你的代码看起来是这样,

function setHeader(){ 
    var questionBox = document.createElement("div"); 
    questionBox.setAttribute("id","questionHolder"); 
    questionBox.setAttribute("style",""background-color":"yellow""); 
    document.body.appendChild(questionBox); 
    var questionElement = document.createElement("h3"); 
    questionElement.setAttribute("id","question"); 
    var questionText = document.createTextNode("Is the sky blue?"); 
    questionElement.appendChild(questionText); 
    questionBox.appendChild(questionElement); 
} 
1

写在CSS文件中的一些风格时,DIV追加到DOM,你在

css文件编写。它将使

#questionHolder { 
    background-color: green; 
    width: 300px; 
    height: 300px; 
} 

#question { 
    background-color: blue; 
} 

演示:http://jsfiddle.net/DfD9y/