Max Max - 1 year ago 124
Javascript Question

jQuery loop without each and callback function

I wish to loop throw jQuery collection without

and callback call.

I have following code

var found1 = false;
$('#Root div.ListItem').each(function( index, d1 ) {
if (group == d1.text()){ found1 = true; }
} );


is set true Next time it is always true. I would like to know how to loop without
and callback like

for(var id in $('#Root div.ListItem')) { ... }


I am not wondering how to break loop.
I do not wish to pass callback in

If I pass jQuery object in loop then I get to many keys.

In that example there might be 1 key for one child element.

Answer Source

Your attempt to use a for-in statement in your fiddle is actually iterating over all of the properties in the jQuery array-like object:

for (var id in $('#Root div.ListItem')) {
    // id is the name of the property

You don't want this; you need to iterate over the elements in the array-like object:

for (var id in $('#root span').toArray()) { // convert to native array
    // id is now an element found by the selector
    $('<div />', {text: $(id).text()}).appendTo($('#out'));

You'll see in the above that the output is what you were expecting.

So, back to your original question. It sounds like you just need to break out of your loop once you've found a match. In case you're wondering how to break out of a jQuery each loop, simply return false; after you set found1 = true;. You shouldn't be afraid to pass in a callback; that callback is just executed for each element in your selector in a regular old for-loop "under-the-hood."

If you really want to write the for-each structure yourself, then something like this would be sufficient:

var found1 = false;
var items = $('#Root div.ListItem').toArray(); // an array of DOM elements
for (var i = 0, j = items.length; i < j; i++) {
    // You can access the DOM elements in the array by index, but you'll
    // have to rewrap them in a jQuery object to be able to call .text()
    if (group == $(items[i]).text()) {
        found1 = true; 
        break; // no need to keep iterating once a match is found

A shorter but slower way to do this might be to use $.grep and check if it found anything:

var found1 = $.grep($('#Root div.ListItem'), function() {
    return group == $(this).text();
}).length > 0;

I wouldn't recommend the latter unless the selector is only returning a handful of elements (e.g. < 50).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download