0

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:

  • in Opera 12.14, Google Chome 24.0.1312.57 m, Safari 5.1.7., Firefox 18.0.2:

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

  • in IE8:

    n = 6

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!

A. Rodas
  • 18,739
  • 7
  • 57
  • 67
primoz060
  • 3
  • 3

1 Answers1

1

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.

adeneo
  • 293,187
  • 26
  • 361
  • 361
  • Oh, I see... `document.write()` overwrites the document content, more about the matter on http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice. So I've reworked to using `console.log` and for `"polje["+i+"] = " + a +"
    "` I've got the result as expected. But still zero for last output `$("div.def_tekst").eq(j).height() + "px, ")`. I intend to create jsfiddle to represent the case.
    – primoz060 Feb 18 '13 at 08:50
  • Eureka, I've got the code that works as expected. The single cause for problems in last few days was in using the damned `document.write()` instead the `console.log()`. Thanks for help to everybody! – primoz060 Feb 18 '13 at 11:11