Removing DOM nodes when traversing a NodeList

前端 未结 7 867
南方客
南方客 2020-12-06 04:54

I\'m about to delete certain elements in an XML document, using code like the following:

NodeList nodes = ...;
for (int i = 0; i < nodes.getLength(); i++)         


        
7条回答
  •  太阳男子
    2020-12-06 05:42

    Old post, but nothing marked as answer. My approach is to iterate from the end, ie

    for (int i = nodes.getLength() - 1; i >= 0; i--) {
        // do processing, and then
        e.getParentNode().removeChild(e);
    }
    

    With this, you needn't worry about the NodeList getting shorter while you delete.

提交回复
热议问题