Question

Is it possible to replace .each() with for..in loop?

$('.my_class').each(function() {
  ...
});

Selector $('.class') is not returning an array of objects, but "just" objects.

You can see this with:

console.log($('.my_class'));

Considering that this is not an array of objects => it is not possible to iterate through all found objects with for..in loop?

Is .each() the only solution?

Was it helpful?

Solution

Selector $('.class') is not returning an array of objects, but "just" objects.

It returns a jQuery object. A jQuery object can be seen as a collection of HTML elements.

As a jQuery object supports the .length property and the [] accessor, it could be seen as an array of HTML Elements, though it is really not.

Considering that this is not an array of objects => it is not possible to iterate through all found objects with for..in loop?

Using the .length and [] directly in the $('.my_class'), you can use for loops.

But don't use for..in, as it iterates through the properties of a JavaScript object, not through the indexes of an array.

Is .each() the only solution?

Being a "solution", of course, depends on the problem. But if you are asking about alternatives, if you must use the for loop, you could:

var elements = $('.my_class'), i, n, element;
for (i = 0, n = elements.length; i < n; i++) {
    element = elements[i];
    // do stuff with element (it is an HTML Element)
}

Though, if you really need an array of elements, you can call the .get() or, better, the .toArray() function in the jQuery object:

// here, elementsArray is really an array of HTML Elements
var elementsArray = $('.my_class').toArray(); 

OTHER TIPS

Selector $('.class') is not returning an array of objects, but "just" objects.

It actually returns a jQuery object, which is an object with an array-like structure.

As mentioned in the comments, you can get array with the elements using $('.class').get().

Since it's still an array, I wouldn't recommend the for...in loop, which should be used to iterate object properties rather than arrays. Even though it will work, I'll recommend a "normal" for loop e.g.

var elements = $('.myclass').get();

for(var i = 0; i < elements.length; i++)
    console.log(elements[i]);

http://jsfiddle.net/5ygMa/

Is this what you're asking for?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top