<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。)