Ram Prabodh Induri
Ram Prabodh Induri

Reputation: 95

error appending child at a specific location using insertBefore()

I am trying to append child always at 2nd position in the div using insertBefore() method, this gave an error.

var j = document.createElement('div');
j.innerHTML = '<p>CreateElement example</p>'
document.insertBefore(j, document.querySelector('.test').children[1]);
<div class="test">
  <div class="first">
    <p>hello world</p>
  </div>
  <div class="second">
    <p>lorem</p>
  </div>
  <div class="third">
    <p>Lorem, ipsum dolor.</p>
  </div>
</div>

The error:

Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.

Upvotes: 0

Views: 122

Answers (1)

Alexander Kiselev
Alexander Kiselev

Reputation: 221

// First we find parent of elements
const parent = document.querySelector('.test');

// then create new div
var j = document.createElement('div');

// insert new div to parent
j.innerHTML = '<p>CreateElement example</p>'
   parent.insertBefore(j, parent.childNodes[2]);
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <script src="script.js" defer></script>
    </head>
    <body>
        <div class="test">
            <div class="first">
                <p>hello world</p>
            </div>
            <div class="second">
                <p>lorem</p>
            </div>
            <div class="third">
                <p>Lorem, ipsum dolor.</p>
            </div>
        </div>
    </body>
    </html>

Upvotes: 1

Related Questions