0

I have tired insertBefore property, it throws script error that

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.

Below code i used.

            parent = document.getElementById(parentid[i]);
            before = document.getElementById(beforeid[i]);
            appenchild1 = document.getElementById(beforeid[i]);
            appenchild2 = document.getElementById(appenchild2id[i]);
            newnode = document.createElement("span");
            newnode.className = "verticalHparent" + btncls[i];
            newnode.style.display = "inherit";
            parent.insertBefore(newnode, before);

Error throwing on insertBefore method, anything wrong?

2
  • 2
    show html structure Commented Mar 22, 2017 at 6:16
  • hard to tell if you did not post your html structure but you can check my answer for working example. Commented Mar 22, 2017 at 6:24

1 Answer 1

2

The error message is pretty explanatory; The before node should be child of parent node on your code.

Here is a working example (look at the html structure):

<div id = "parent">

    <div id = "child_1">child1</div>
    
</div>

<button onclick="createNewElement()">Create New Child</button>

<script type="text/javascript">

    function createNewElement(){

        var parent = document.getElementById("parent");
        var before = document.getElementById("child_0");
        
        var newnode = document.createElement("span");
        newnode.className = "verticalHparent";
        newnode.style.display = "inherit";
        newnode.innerHTML = "child2";
        parent.insertBefore(newnode, before);
    
        
    }
    
 
</script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.