Yarin
Yarin

Reputation: 183989

Using jQuery selectors to iterate through DOM elements

Can someone tell me why this won't work?

var top = 0;
for (divToPosition in $('.positionableDiv')) {
   divToPosition.css('top',top+'px');
   top = top + 30;
}

Upvotes: 3

Views: 8731

Answers (5)

user229044
user229044

Reputation: 239551

The correct way to iterate over a set of matched elements is with .each, as other answers have mentioned. Attempting to use a for..in loop will iterate over the properties of the jQuery object, not the elements it matched.

To improve slightly on some of the other .each examples, you could omit the top variable to clean things up a little. The first parameter to .each is in the index of the element within the set of matched elements; you could achieve the same thing by multiplying it by 30 at each step. There is no incrementing and no top variable cluttering things up:

$('.positionableDiv').each(function(i) {
    $(this).css('top', (i * 30) + "px");
});

Upvotes: 6

Šime Vidas
Šime Vidas

Reputation: 186103

This would work:

var top = 0;
for (var pdiv in $('.positionableDiv').get()) {
   $(pdiv).css('top', top + 'px');
   top = top + 30;
}

Basically, you use get() to retrieve the array of elements.

Upvotes: 3

Atanas Korchev
Atanas Korchev

Reputation: 30661

The "for (var key in obj)" is suitable for iterating the members of an object. It works for native JavaScript arrays as long as their prototype is not extended. A jQuery object may look as a native JavaScript array but it is not hence "for ( in )" fails.

You can use .each to iterate over a jQuery object: var top = 0;

$('.positionableDiv').each(function() {
     $(this).css('top', top);
     top += 30;
});

Upvotes: 2

Orbling
Orbling

Reputation: 20612

The $('.positionableDiv') in your statement is a jQuery object with a great many properties. What you want is to iterate through the matched elements which is not done that way.

Try:

var top = 0;
$('.positionableDiv').css('top', function(index, value) {
    var cTop = top;
    top = top + 30;
    return cTop + 'px';
});

Upvotes: 1

Quintin Robinson
Quintin Robinson

Reputation: 82375

The first reason would be the misuse of the for loop.

jQuery has an idiom for looping over selected elements..

var top = 0;
$('.positionableDiv').each(function() {
   $(this).css('top',top+'px');
   top = top + 30;
});

Please take a look at for...in for a better understanding of the way a for...in loop works in javascript, it does not enumerate in the same way as say .NET or Java.

From Article:

Although it may be tempting to use this as a way to iterate over an Array, this is a bad idea.

Upvotes: 14

Related Questions