Search code examples
javascripthtmlappendchild

appending child div to its parent dynamically in the constructor


I'm having issues using appendchild() to append a div within a div. If possible, I would like to avoid using jquery.I'm using constructor functions for both the parent and child divs.

<script>

    var loopi = 0;


    function codeDiv(){
        codeDiv1 = document.createElement("div");
        codeDiv1.style.height  = "100px";
        codeDiv1.style.width = "200px";
        codeDiv1.style.border = "thick solid black";

    }

    function functionObject(){
        var functionDivObject = document.createElement("div");
        functionDivObject.style.width = "500px";
        functionDivObject.style.height = "500px";
        functionDivObject.style.border = "thick solid black";
        document.body.appendChild(functionDivObject);
        var codeDiv1 = new codeDiv();
        functionDivObject.appendChild(codeDiv1);  //I am having the problem here
        functionDivObject.id = "functionDiv"+loopi;
        loopi++;
    }
    loopi = 0;


    var temp = new functionObject();

</script>

Solution

  • Your browser console should have an error like Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'., since the appendChild() method needs a dom element reference as its argument.

    In your case you are passing a codeDiv instance to it.

    You need to return the new div from codeDiv

    function codeDiv() {
        var codeDiv1 = document.createElement("div");
        codeDiv1.style.height = "100px";
        codeDiv1.style.width = "200px";
        codeDiv1.style.border = "thick solid black";
        return codeDiv1;
    
    }
    

    Demo: Fiddle