如何用javaScript实现两个div(节点)互换位置

直接贴代码

如果有任何可以改进的地方,欢迎评论区留言!共同努力加油

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  #d1{
     
    background-color: aliceblue;
    width: 40px;
    height: 40px;
  }
  #d2{
     
    background-color: aqua;
    width: 40px;
    height: 40px;

  }
</style>
<body>
  <div id="father">
  <div id="d1">
d1
  </div>
  <div id="d2">
    d2
  </div>
  <div id="d3">
    d3
  </div>
  <div id="d4">
    d4
  </div>
  <div id="d5">
    d5
  </div>
</div>
</body>
<script>
  var newObj = document.createElement("div");
  newObj.setAttribute("id","new");
  newObj.innerHTML = "哈哈";
  var d1 = document.getElementById("d1");
  var d2 = document.getElementById("d2");
  var d3 = document.getElementById("d3");
  var d4 = document.getElementById("d4");
  var d5 = document.getElementById("d5");
  d1.parentElement.insertBefore(newObj,d5);
  d1.parentElement.insertBefore(d5,d2);
  d1.parentElement.insertBefore(d2,newObj);
  d1.parentElement.removeChild(newObj);
</script>
</html>

完毕,博主用的是inserBefore方法做的 里面有两个参数,第一个是新的节点(你想要插入的节点),第二个是被插入的节点(被插在前面的节点)

你可能感兴趣的:(javascript)