JavaScript 添加一个元素标签
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<div id="div1">
<p id="p1">这是一个段落。</p>
<p id="p2">这是另外一个段落。</p>
<button onclick="creatEle()">
添加元素
</button>
</div>
<script>
function creatEle() {
var para = document.createElement("p");
para.id = "id1"
para.classList.add("class1");
para.classList.add("class2");
para.style.cssText="width:200px;height:200px;background:#CC3399;text-align:center;line-height:220px"
var node = document.createTextNode("添加元素");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
}
</script>
</body>
</html>
效果