insertBefore() - how do I use it?

First, some docs:


And my code:

Basically, my DOM structure is kind of like this:

-- .container (parent)
|- .flex one (child)
|- .flex two (child)
|- .button #flexbutton (child)

I want to use insertBefore to insert new .flex one behind #flexbutton. I tried something like this:

var receiver = document.getElementById("flexbutton") //get the button
var container = document.querySelector(".container") //get the container 

receiver.onclick = function(event) { //preparing onclick...
var el = document.createElement("div") //create elem
el.class = "flex two" //set class 
receiver.insertBefore(el, container.childNodes[container.childNodes.length - 4]) 
//^ select the second to last element.
console.log("test")

I subtract four from the length, because each div element also has an empty text child - I need to traverse the button, its text child and then the target element’s text child to select the actual element.

But i get this:

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.
    at HTMLDivElement.receiver.onclick

What am I missing?

Edit: According to this link you need to “call insertBefore” on the parent el. I’m trying that right now.

I got the solution!

Basically, I had to use className instead of class, and call insertBefore on the parent elem.

2 Likes