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