如何迭代更改的子集

时间:2016-01-05 17:31:27

标签: javascript children

我正在使用vanilla javascript迭代元素的子元素,根据类删除它们。但是,我正忙着处理嵌套元素。

以下是代码的简化版本:

var replacements = [];
var children = el.getElementsByTagName('*');
for(var i = 0; i < children.length; i++) {
    var child = children[i];
    if(should_delete(child)) { /*just checking for the class "delete-me"*/
        replacements.push(child.outerHTML);
        var filler = document.createComment('deleted');
        child.parent.replaceChild(child);
    }
}

在这结束时,我需要一个包含注释的元素,其中发生了替换,以及一组与一组注释匹配的替换值。

但是,我遇到以下html的问题

<div class="wrap">
    <div class="outer">
        <div class="delete-me">test</div>
        <div class="delete-me">
            <div class="delete-me">test2</div>
            <div class="delete-me">test3</div>
        </div>
        <div class="delete-me">test4</div>
    </div>
    <div class="delete-me">test5</div>
</div>

最终结果应该是:                                                                            

使用数组:

[
    '<div class="delete-me">test</div>',
    '<div class="delete-me"><div class="delete-me">test2</div><div class="delete-me">test3</div></div>',
    '<div class="delete-me">test4</div>',
    '<div class="delete-me">test5</div>'
]

但相反,它似乎很早就失败了,因为子伪数组一直在变异,以匹配DOM的变化状态。

如何允许子伪数组随DOM更改,同时仍然平滑地迭代它,而不是存储已经替换的元素的内容?

2 个答案:

答案 0 :(得分:0)

想出来......

我不需要使用实时集合或静态数组,而是需要通过dom树递归,在我去的时候删除。

var replacements = [];
var processChildren = function(children) {
    var children_a = []; // this array exists so that children wont change as we delete elements
    for(var i = 0; i < children.length; i++) {
        children_a.push(children[i])
    }
    for(var i = 0; i < children_a.length; i++) {
        var child = children_a[i];
        if(should_delete(child)) { /*just checking for the class "delete-me"*/
            replacements.push(child.outerHTML);
            var filler = document.createComment('deleted');
            child.parent.replaceChild(filler, child);
        } else {
            processChildren(child.children);
        }
    }
}
processChildren(el.children);

答案 1 :(得分:-1)

向后迭代。

Sub TestColl()
    Dim TestCollection As Collection
    Set TestCollection = CreateColl()
    LoopThruColl TestCollection
End Sub
Function CreateColl() As Collection
    Dim MyColl As Collection
    Set MyColl = New Collection

    Dim i As Integer
    For i = 1 To 5
        MyColl.Add i * 2
    Next i
    Set CreateColl = MyColl
End Function
Sub LoopThruColl(CollToLoop As Collection)
    Dim i As Integer
    For i = 2 To CollToLoop.Count
        Debug.Print i, CollToLoop.Item(i - 1), CollToLoop.Item(i)
    Next i
End Sub

这将确保即使您最终删除元素,也会依次看到每个元素。你甚至可以添加元素并让它工作得很好,只要这些添加的元素在添加它们之后。