Search code examples
javascripthtmlclassname

why changing classname in a list of object removes itens from the list


You will see that only 2 td object lost the clasNname. Why the variable "many" looses a itens at each className=""? Can anyone help me? Thank you.

    <!DOCTYPE html>
    <html>
    <head>
        <title>Why?</title>
        <style>
            .f{background:lightblue;}
            .g{background:lightcoral;}
        </style>
    </head>
    <body>
        <table id="t" style="border:1px solid black">
            <tr>
                <td class="f">1</td>
                <td class="f">2</td>
                <td class="f">3</td>
                <td class="f">4</td>
            </tr>
        </table>

        <script>
            many = document.getElementById("t").getElementsByClassName("f");
            document.write("initial length of many="+many.length+"<br>");
            for (var x = 0; x < many.length; x++) {
                many[x].className='';
                document.write("loop x="+x+" many.length="+many.length+"<br>");
            }
            document.write("final length of many="+many.length+"<br>");
        </script>
    </body>
</html>


Solution

  • The getElememtsByClassName() method returns a live NodeList, therefore if you remove the class-name you searched by those elements that no longer have that class-name are immediately removed from that NodeList held in the many variable.