DOM -如何移动HTML元素

DOM - How to move HTML elements?

本文关键字:移动 HTML 元素 何移动 DOM      更新时间:2023-09-26

我想创建一个新元素(a div),但不是将其创建为最后一个元素,而是将其创建在两个元素之间。我创建了下面这个简化的代码来表示我想要做的事情:

<!DOCTYPE html>
<html lang="ca">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script>
  function createDiv() {
      var newDiv = document.createElement("div");
      var txt = document.createTextNode("I'm the second div");
      newDiv.appendChild(txt);
      document.body.appendChild(newDiv);
  }
  </script>
</head>
<body>
  <div class="first">
    <p>I'm the first div</p>
  </div>
  <div class="third">
    <p>I'm the third div</p>
  </div>
  <button type="button" name="button" onclick="createDiv()">Create the second Div</button>
</body>
</html>

请记住,我只想使用DOM,而不是jQuery

您可以通过在第三个div之前插入以下操作

  function createDiv() {
      var newDiv = document.createElement("div");
      var txt = document.createTextNode("I'm the second div");
      newDiv.appendChild(txt);
      var thirdDiv = document.getElementById("thrid");
      thirdDiv.parentNode.insertBefore(newDiv, thirdDiv);
  }
<!DOCTYPE html>
<html lang="ca">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div class="first">
    <p>I'm the first div</p>
  </div>
  <div id="thrid" class="third">
    <p>I'm the third div</p>
  </div>
  <button type="button" name="button" onclick="createDiv()">Create the second Div</button>
</body>
</html>