<!DOCTYPE html>
<html>
<head>
<title>Deleting Nodes</title>
<script src="script02.js"></script>
</head>
<body>
<form action="#">
<p><textarea id="textArea" rows="5" cols="30"></textarea></p>
<input type="submit" value="Add some text to the page">
</form>
<a id="deleteNode" href="#">Delete last paragraph</a>
</body>
</html>
window.onload = initAll;
function initAll() {
document.getElementsByTagName("form") [0].onsubmit = addNode;
document.getElementById("deleteNode").onclick = delNode;
}
function addNode() {
var inText = document.getElementById ("textArea").value;
var newText = document.createTextNode (inText);
var newGraf = document.createElement ("p");
newGraf.appendChild(newText);
var docBody = document.getElementsByTagName("body")[0];
docBody.appendChild(newGraf);
return false;
}
function delNode() {
var allGrafs = document.getElementsByTagName("p");
if (allGrafs.length > 1) {
var lastGraf = allGrafs.item (allGrafs.length-1);
var docBody = document.getElementsByTagName("body")[0];
docBody.removeChild(lastGraf);
}
else {
alert("Nothing to remove!");
}
return false;
}
这里获取最后一个p节点,使用item,这个需要注意。
专业墙纸贴纸厨房用具装饰出售,本人网店经营
博客对你有用记得访问下哦,增加下访问量,如有需要可以下单购买哦^_^。https://item.taobao.com/item.htm?id=570637716145