Failed to execute 'insertBefore' on 'Node'

Viewed 73

I'm trying to create a simple html page where new div will be added after previous (in dedicated "workspace"). The goal is achieved and all new <divs> are created properly

<body>

...

<div id="workspace" >

<script type="text/javascript">
var my_div = document.getElementById("workspace");
var newDiv = null;
function addElement()    {

newDiv = document.createElement("div");
newDiv.innerHTML = "<h7>Hi there and greetings!</h7>";
newDiv.style.width = "200px";
newDiv.style.height = "50px";
newDiv.style.background = "red";
my_div.appendChild(newDiv);
my_div.insertBefore(newDiv, workspace);

}
</script>

<a href="#" onclick="addElement()">ADD new  greeting</a>
</div>
...
</body>

However in my console I get an 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.

I'm completely new in JS but I can't find any simple explanation. What is wrong with such code? Where does this error come from? No more JS is used in whole document...

1 Answers

This is because workspace is not defined. You can add a new variable to store the latest div that you saved. Then check if it's not null (it's null when you click on the link for the first time. Then you can use insertBefore with the last div as the second argument

<div id="workspace">
    <script type="text/javascript">
        var my_div = document.getElementById("workspace");
        var newDiv = null;
        var lastDiv = null
        function addElement() {

            newDiv = document.createElement("div");
            newDiv.innerHTML = "<h7>Hi there and greetings!</h7>";
            newDiv.style.width = "200px";
            newDiv.style.height = "50px";
            newDiv.style.background = "red";
            my_div.appendChild(newDiv);
            if (lastDiv) {
                my_div.insertBefore(newDiv, lastDiv);
            }
            lastDiv = newDiv

        }
    </script>


    <a href="#" onclick="addElement()">ADD new greeting</a>
</div>
Related