0

I want to create a new element (a div) but instead of creating it as the last element, I want to create it between two elements. I created this simplified code of what I want to do:

<!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>

Keep in mind that I want to use DOM only, not jQuery.

JJJ
  • 32,902
  • 20
  • 89
  • 102
DavidMM
  • 187
  • 3
  • 11

1 Answers1

0

You can do the following by inserting before the third 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>
YaBCK
  • 2,949
  • 4
  • 32
  • 61