createElement(創(chuàng)建新元素):
document.createElement(nodeName)
createTextNode(創(chuàng)建新文本):
document.createTextNode(text)
appendChild(添加子節(jié)點(diǎn)):
parent.appendChild(child)
舉個(gè)例子吧:
創(chuàng)建一個(gè)簡(jiǎn)單的項(xiàng)目來(lái)簡(jiǎn)單了解一下用法:
test.html文件:
<!DOCTYPE <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="test"></div>
<script type="text/javascript" src="example.js"></script>
</body>
</html>
example.js:
var p = document.createElement("p");//創(chuàng)建元素節(jié)點(diǎn)P
var txt = document.createTextNode("Hello World!");//創(chuàng)建內(nèi)容為“Hello World!”的文本節(jié)點(diǎn)
var test = document.getElementById("test");//獲取html頁(yè)面上的ID為“test”的元素節(jié)點(diǎn)
p.appendChild(txt);//為元素節(jié)點(diǎn)P添加一個(gè)類型為文本節(jié)點(diǎn)的子節(jié)點(diǎn)“txt”;
test.appendChild(p);//為元素節(jié)點(diǎn)test添加一個(gè)類型為元素節(jié)點(diǎn)的子節(jié)點(diǎn)“P”;