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!

2
  • can you create jsfidde that represent the problem ? Commented Feb 17, 2013 at 18:30
  • What happens if you log to the console instead of using document.write()? Commented Feb 17, 2013 at 18:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh, I see... document.write() overwrites the document content, more about the matter on stackoverflow.com/questions/802854/…. So I've reworked to using console.log and for "polje["+i+"] = " + a +"<br>" 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.
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.