正确遍历节点 - javascript childNodes [英] Traversing nodes correctly - javascript childNodes
问题描述
我正在尝试将以下代码片段用于每个子节点一次。该函数还根据逻辑删除节点,对于多个子节点,它似乎永远不会遍历每个子节点。
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);
}
}
}
在特殊情况下我有4Div作为孩子,这只删除了两个DIV而不是全部。
我假设长度也在不断变化,因此它无法让所有孩子都接受。
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?
推荐答案
你是完全正确的:问题是你在 NodeList <时使用静态索引您引用的/ code>(
target.childNodes
)是实时的:当您删除其中一些子节点时,它会更新。
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.
最简单的方法是创建元素子节点的静态列表。你似乎试图这样做,但Javascript有动态类型,所以 var children = new Array();
基本上没有任何用处。它不会强制 NodeList
成为一个数组。你想要的功能是 数组.from
:
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);
}
}
请注意 Array.from
是一个新功能,所以你应该为旧浏览器提供一个垫片。
Note that Array.from
is a new-ish function, so you should provide a shim for older browsers.
这篇关于正确遍历节点 - javascript childNodes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!