Traversing nodes correctly - javascript childNodes

可紊 提交于 2019-12-20 07:37:12

问题


I am trying to make following piece of code to work for each child node once. THe function is also deleting the node as per logic, for more than one child node it never seems to traverse to each child node.

//Deleting from child node
            var target =document.getElementById(element.name).childNodes[0];            
            if(target.hasChildNodes())
            {
              var children = new Array();
              children = target.childNodes;
              for(child in children)
              {
                if(children[child].tagName == 'DIV'){
                    //target.removeChild[child];
                    var deleteChild = document.getElementById(target.childNodes[child].id);
                    deleteChild.parentNode.removeChild(deleteChild);
                }
              }
            }

In a special case i have 4 "Div" as child, this only remove two DIV and not all. I assume as the length is also changing constantly, hence it's not able to get to all children.

Is this correct way of traversal, am i missing something obvious?


回答1:


You are exactly right: the problem is that you are using a static index when the NodeList to which you refer (target.childNodes) is live: it is updated when you remove some of those child nodes.

The simplest way to do this is to make a static list of the child nodes of the element. You seem to be trying to do this, but Javascript has dynamic typing, so var children = new Array(); essentially does nothing useful. It does not coerce the NodeList into becoming an array. The function you want is Array.from:

var children = Array.from(target.childNodes);
var child; // don't forget to declare this variable
for(child in children)
{
    if(children[child].tagName == 'DIV'){
        //target.removeChild[child];
        var deleteChild = target.childNodes[child]; // simplify
        deleteChild.parentNode.removeChild(deleteChild);
    }
}

Note that Array.from is a new-ish function, so you should provide a shim for older browsers.



来源:https://stackoverflow.com/questions/42130063/traversing-nodes-correctly-javascript-childnodes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!