Traversing nodes correctly - javascript childNodes

后端 未结 1 1826
春和景丽
春和景丽 2021-01-29 02:22

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

1条回答
  •  北海茫月
    2021-01-29 03:02

    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.

    0 讨论(0)
提交回复
热议问题