使用appendChild,不管是用getElementById().appendChild()还是用document.body.appendChild()都不能一次添加多个节点:
<html >
<head>
<title>A Simple Page</title>
</head>
<script language="javascript">
function newElement(){
var newElem = document.createElement("p");
newElem.setAttribute("id","newP");//newElem.id = "newP";
var newText = document.createTextNode("This is the second paragraph.");
newElem.appendChild(newText);
for(var i=0;i<5;i++)
document.getElementById("paragraph1").appendChild(newElem);
//document.getElementById("emphasis1").appendChild(newElem);
//document.body.appendChild(newElem);
}
</script>
<body>
<p id="paragraph1">
This is the
<em id="emphasis1">
one and only
</em>
paragraph on the page.
</p>
<input name="" type="button" value="Click here!" onclick="newElement()" />
</body>
</html>
点击"Click here!"后输出结果是:
This is the one and only paragraph on the page.
This is the second paragraph.