<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button id="btn">按钮</button>
<div class="box1">盒子1</div>
<script>
var btn = document.getElementById("btn");
var box1 = document.querySelector(".box1");
var box2Div = document.createElement("div");
box2Div.className = "box2";
btn.onclick = function(){
insertAfter(box2Div, box1);
}
function insertAfter(newElement, targetElement){
var parent = targetElement.parentNode;
console.log(parent);
if (parent.lastChild == targetElement) {
// 如果最后的节点是目标元素,则直接添加。因为默认是最后
parent.appendChild(newElement);
}
else
{
parent.insertBefore(newElement, targetElement.nextSibling);
//如果不是,则插入在目标元素的下一个兄弟节点 的前面。也就是目标元素的后面
}
}
</script>
</body>
</html>