for loop not executing all loops in js

I have this code,

var v = 'asdasdadsa<img src="ttttttt">asdasdadsa';
var x = $('<div></div>').append(v);
var t = $('<div></div>').get(0);
var z = x.get(0).childNodes;
var max = 20;
var length = 0;
for(i=0;i<z.length;i++){
    console.log(z[i].nodeType);
    // if(z[i].nodeType == 3){
    //     var prev_length = length;
    //     length += z[i].length; 
    //     if(length > max){
    //         var val = z[i].nodeValue;
    //         t.appendChild(document.createTextNode(val.substring(0,max-prev_length)));
    //         break;
    //     }else{
    //         t.appendChild(z[i]);
    //     }
    // }
    if(z[i].nodeType == 1){
        if(length > max){
            // break;
        }else{
            t.appendChild(z[i]);
        }
    }
}
console.log(t);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The for loop above not executing all three loops, breaking when second if condition is executed.

If you comment the second if condition, it executes all three loops.

So the problem must be in second if condition.

Answer

The act of appending an element to t from z is changing the length of z. This can be demonstrated with some console.log. You can fix that (although probably break something else) by caching the length of z before the loop.

var v = 'asdasdadsa<img src="ttttttt">asdasdadsa';
var x = $('<div></div>').append(v);
var t = $('<div></div>').get(0);
var z = x.get(0).childNodes;
var max = 20;
var length = 0;
console.log("len before",z.length);
for(i=0;i<z.length;i++){
    //console.log(i,z[i].nodeType);
    // if(z[i].nodeType == 3){
    //     var prev_length = length;
    //     length += z[i].length; 
    //     if(length > max){
    //         var val = z[i].nodeValue;
    //         t.appendChild(document.createTextNode(val.substring(0,max-prev_length)));
    //         break;
    //     }else{
    //         t.appendChild(z[i]);
    //     }
    // }
    if(z[i].nodeType == 1){
        if(length > max){
            // break;
        }else{
           t.appendChild(z[i]);
        }
    }
    console.log("len after",z.length);
}
console.log(t);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Leave a Reply

Your email address will not be published. Required fields are marked *