通过节点实现图片的增加和减少
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>节点的添加和删除</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
.div {
width: 600px;
height: auto;
}
img {
width: 400px;
height: 400px;
border: none;
}
</style>
<body>
<div id="div">
<img src="../dongman.jpg" alt="" id="img">
</div>
<button id="add">添加图片</button>
<button id="deltey">删除图片</button>
</body>
<script>
//获取id为div的节点
var div = document.getElementById("div");
add.onclick = function(){
//创建新的节点
var newimage = document.createElement('img');
//新节点配置属性
newimage.setAttribute('src','../dongman.jpg');
div.appendChild(newimage);
}
deltey.onclick = function(){
console.log(div);
if(div.firstChild.nextSibling.nodeName!="#text"){//判断是否为为文本节点,如果不是,则删除该节点,文本节点一定是元素节点的子节点.
div.removeChild(div.firstChild.nextSibling.nextSibling.nextSibling);
}
}
</script>
</html>