Javascript .removeChild() only deletes even nodes?

Posted by user1476297 on Stack Overflow See other posts from Stack Overflow or by user1476297
Published on 2012-06-23T03:13:48Z Indexed on 2012/06/23 3:15 UTC
Read the original article Hit count: 100

Filed under:

first posting.

I am trying dynamically add children DIV under a DIV with ID="prnt". Addition of nodes work fine no problem. However strange enough when it comes to deleted nodes its only deleting the even numbered nodes including 0. Why is this, I could be something stupid but it seem more like a bug. I could be very wrong.

Please help Thank you in advance.

    <script type="text/javascript">

        function displayNodes()
        {
            var prnt = document.getElementById("prnt");
            var chlds = prnt.childNodes;
            var cont = document.getElementById("content");

            for(i = 0; i < chlds.length; i++)
            {
                if(chlds[i].nodeType == 1)
                {

                    cont.innerHTML +="<br />";
                    cont.innerHTML +="Node # " + (i+1);
                    cont.innerHTML +="<br />";
                    cont.innerHTML +=chlds[i].nodeName;
                    cont.innerHTML +="<br />";

                }
            }
        }

        function deleteENodes()
        {
            var prnt = document.getElementById("prnt");
            var chlds = prnt.childNodes;


            for(i = 0; i < chlds.length; i++)
            {

                    if(!(chlds[i].nodeType == 3))
                    {
                        prnt.removeChild(chlds[i]);
                    }

            }


        }

        function AddENodes()
        {
            var prnt = document.getElementById("prnt");

           //Only even nodes are deletable PROBLEM

            for(i = 0; i < 10; i++)
            {

                var newDIV = document.createElement('div');
                newDIV.setAttribute("id", "c"+(i));

                var text = document.createTextNode("New Inserted Child "+(i));
                newDIV.appendChild(text);
                prnt.appendChild(newDIV);

            }
        }

    </script>

    <title>Checking Div Nodes</title>
</head>


<body>

    <div id="prnt">
        Parent 1

    </div>

    <br />
    <br />
    <br />

   <button type="button" onclick="displayNodes()">Show Node Info</button>
   <button type="button" onclick="deleteENodes()">Remove All Element Nodes Under Parent 1</button>
   <button type="button" onclick="AddENodes()">Add 5 New DIV Nodes</button>

    <div id="content">

    </div>
</body>

© Stack Overflow or respective owner

Related posts about JavaScript