views:

79

answers:

3

I have the following code block code when the document is ready:

$(document).ready(function() {
    createDivs(); // creates some divs with class 'foo';

    // iterate
    $(".foo").each(function(index) {
        alert(index + " - " + $(this).text());
    });
}

I find that the "iterate" part misses the divs I created in the createDivs() method entirely! Is there some timing issue I'm not aware of? Why doesn't jquery see the divs that were just created?

A: 

The timing is not the issue. Maybe createDivs() doesn't add the elements to the DOM?

Jakob Kruse
This answer is more appropriate as a comment to the question.
Crescent Fresh
A: 

I've found that Javascript is like a bull in an F1 racer when it comes to executing code. There's no making it wait to execute code in any particular chain.

You should probably create a situation where createDivs() is able to fire any dependent code after it is complete vis-a-vis a callback. Without seeing the createDivs code, it's tough to give you a way to implement it.

UPDATE

Really only applies if you're doing an asynchronous call (according to my friends below).

dclowd9901
As far as I understand, if you're not doing any asynchronous work, Javascript should be executing the code sequentially. Of course, if createDivs goes off and calls something on the server and actually creates the divs in the success callback or something along those lines, then it's all up in the air.
justkt
If you've ever tried to do this: `$('.somediv').slideUp();$('.somediv').remove();`, you know first hand code sequence in JS. I'm not sure if that falls into your definition of asynchrony, but it surprised me when I first saw it.
dclowd9901
@dclowd9901 - That is asynchronous, animations are performed on intervals.
Nick Craver
Ah, good to know.
dclowd9901
Silly me, createDivs() was indeed creating them asynchronously in an AJAX callback.
ripper234
+1  A: 

In my experience DOM manipulation can act asynchronous at times, possibly due to optimization by the browser, my usual solution is to have createDivs() return the divs created then use the returned elements aswell

var divs = createDivs();
$('.foo').and(divs).each(function(){
    //happy fun time
})
Kristoffer S Hansen