javascriptnodelistxmlnodelist

NodeList Data is not getting removed


I have an array object which has 3 objects. I want to remove all the objects except the first one.

Here is my data which I got from XML:

mrArr[0] = <Data>
                <G> "Val" = "5" </G>
           </Data>  
mrArr[1] = <Data>
                <G> "Val" = "6" </G>
           </Data>
mrArr[2] = <Data>
                <G> "Val" = "7" </G>
           </Data>

I have created a loop to try and do this but it is only removing one element. What is wrong with my loop?:

for(var i = 1; i < myArr.length; i++){
    myArr[i].remove();
}

It is removing only one element.


Solution

  • Since you're mutating the array after every iteration, array.length keeps decreasing. Hence, in your example, the loop gets executed only once, thereby removing only one element.

    Here's a working example of what you're trying to achieve.

    var nodes = document.getElementsByTagName('div');
    
    console.log('Before removal:', nodes);
    
    while (nodes.length > 1) {
      var node = nodes[nodes.length - 1];
      node.parentNode.removeChild(node);
    }
    
    console.log('After removal:', nodes);
    <div id="div-01">Here is div-01</div>
    <div id="div-02">Here is div-02</div>
    <div id="div-03">Here is div-03</div>