在元素前后添加创建的元素
话不多说,直接上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sanai_1992</title>
<style>
.item{ width: 100px; height: 100px; background-color: linen; }
.item2{ width: 200px; height: 100px; background-color: lightblue; }
</style>
</head>
<body>
<div id="container" class="container">
<div class="item" id="item"></div>
</div>
</body>
<script>
/**
* name: addDomTopOrBottom => 在元素前后添加元素
* params => ele:参照元素
* params => newDom:需要插入的元素
* params => position = 'bottom' : 插入位置 top:ele元素前 bottom:ele元素后(默认)
* */
function addDomTopOrBottom(ele, newDom, position = 'bottom') {
let parent = ele.parentNode;
if(position === 'top') {
parent.insertBefore(newDom, ele)
}else if(position === 'bottom'){
if (parent.lastChild === ele) {
parent.appendChild(newDom);
} else {
parent.insertBefore(newDom, ele.nextSibling)
}
}
}
let dom = document.createElement("div");
dom.className = 'item2';
let dom1 = document.createElement("div");
dom1.className = 'item2';
addDomTopOrBottom(document.getElementById("item"),dom,'top')
addDomTopOrBottom(document.getElementById("item"),dom1)
</script>
</html>
运行结果:
![运行结果,在item前后均添加了item2](https://img-blog.csdnimg.cn/83b55dfd560b4edfa646a10853bdb734.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NhbmFpXzE5OTI=,size_16,color_FFFFFF,t_70)