Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery loop without each and callback function

I wish to loop throw jQuery collection without each and callback call.

I have following code

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

if(found1){
    return;
}

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

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

UPDATE

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

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

http://jsfiddle.net/LwTGU/

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

like image 632
Max Avatar asked Jan 16 '14 23:01

Max


People also ask

Why do we need callback functions in jQuery?

Since jQuery is a JavaScript library and JavaScript statements are executed sequentially, with animations, it might happen that even before the effect is completed, the following lines of code get executed. This can create errors due to overlapping of effects. Thus, to prevent such scenarios, jQuery needs callback functions.

How to avoid jQuery each method?

So I present you with the 7 ways to avoid jQuery Each method with an equivalent JavaScript .forEach () method on your website. The 1 st parameter is a ‘Required’ one and is a callback function that runs for each element of the array. This callback function has 3 parameters - function (currentValue, index, arr)

How do you use each each in jQuery?

.each () is used directly on a jQuery collection. It iterates over each matched element in the collection and performs a callback on that object. The index of the current element within the collection is passed as an argument to the callback.

What are the arguments passed to the callback method in JavaScript?

The arguments passed to the callback are the index of the matched element within the set and the result of the 'getter' signature of the method.


3 Answers

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).

like image 102
Cᴏʀʏ Avatar answered Oct 31 '22 13:10

Cᴏʀʏ


It sounds like you want to stop processing when you meet some condition. You can do that with each by returning false when the condition is met:

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

You can also iterate over the return value of $('#Root div.ListItem') like it's any other array (if you insist on not using each).

like image 34
Wayne Avatar answered Oct 31 '22 15:10

Wayne


As I do not have the necessary reputation (50), I was not able to comment on the accepted answer. However, I do not believe that the following code will work as expected:

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'));
}

Unless I'm missing something, "id" would be an integer representing the iterated array index, not the actual array element. If so, $(id) would not point to a valid jquery object. Instead, wouldn't it need to be something like this?

for (var id in $('#root span').toArray()) { // convert to native array
    // id is now an element found by the selector
    $('<div />', {text: $($('#root span')[id]).text()}).appendTo($('#out'));
}
like image 39
kevinmkr Avatar answered Oct 31 '22 15:10

kevinmkr