primoz060
primoz060

Reputation: 3

jquery not working as expected in javascript for loop

I've encountered the problem of using jQuery inside the javascript for loop. After more than 24 hours investigating I've decided to post the core of the problem. I've shrunk the code to the simple example:

var a, i, j;
var n = $("div.kategorija_tekst").length;
document.write("n = " + n + "<br>");
for (i = 0; i < n; i++){
    a = $("div.kategorija_tekst").length;
    document.write("polje["+i+"]  = " + a +"<br>");
    for (j = 0; j < a; j++){
        document.write($("div.def_tekst").eq(j).height() + "px, ");
    }
}

I've got:

But it should be expected as:

n = 6, polje[0] = 6, 28px, 28px, polje[1] = 6, 28px, 28px, polje[2] = 6, 28px, 28px, polje[3] = 6, 28px, 28px, polje[4] = 6, 28px, 28px, polje[5] = 6, 28px, 28px,

Strange! Why has the a variable inside the for loop got zero value? Why are the height() values (in the nested for loop) completely missing? Why IE8 hasn't succeeded to write even this line(s)?

("polje["+i+"]  = " + a + "<br>")

Any help would be greatly appreciated!

Upvotes: 0

Views: 77

Answers (1)

adeneo
adeneo

Reputation: 318182

document.write overwrites the documents content:

var a, i, j;
var n = $("div.kategorija_tekst").length; 
document.write("n = " + n + "<br>"); //document no longer has any elements
for (i = 0; i < n; i++){
    a = $("div.kategorija_tekst").length; // returns null, no such thing in document
    document.write("polje["+i+"]  = " + a +"<br>");
    for (j = 0; j < a; j++){
        document.write($("div.def_tekst").eq(j).height() + "px, ");
    }
}

You're overwriting the document content, so the next selector always returns null.

Upvotes: 1

Related Questions