DOM - 如何移动HTML元素?

时间:2016-10-14 08:49:40

标签: javascript html

我想创建一个新元素(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。

1 个答案:

答案 0 :(得分:0)

您可以通过在第三个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>