<html>
<body>
<article>
<p>這是第一段。</p>
</article>
<script type="text/javascript">
window.onload = function(){
var p1 = document.createElement("p");
var txt1 = document.createTextNode("2017");
p1.appendChild(txt1);
var parent = document.getElementsByTagName("article")[0];
var p2 = document.getElementsByTagName("p")[0];
parent.insertBefore(p1,p2);
p1.setAttribute("style","background-color:blue;color:red;width:100px;height:200px")
}
</script>
</body>
</html>
步驟:
1.創建一個新的元素節點p;(使用document.createElement(element)方法。)
2.創建一個新的文本節點;(使用document.createTxetNode(string)方法。)
3.將新建的文本節點插入新建的元素節點;(使用element.appendChild(node)方法,可向元素節點的末尾添加子節點。)
4.獲取新建元素節點的父節點;(使用document.getElementsByTagName(element)方法。)
5.獲取新建元素插入位置的下一個兄弟節點;
6.插入新建元素;(使用element.insertBefore(newnode,existingnode)方法。)
7.爲新建元素設置css屬性。(使用element.setAttribute(attribute,attribute-value)方法。)
8.綁定onload事件。(window.onload。)