Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: `:eq(i) ` Selection

I'm trying to assign 10 div class hi with different height.

I know I can do it this way.

$(".hi:eq(0)").css("height",n[0]);
$(".hi:eq(1)").css("height",n[1]);
$(".hi:eq(2)").css("height",n[2]);
   ..........
$(".hi:eq(9)").css("height",n[9]);

However, when I try generating them by using a for loop it doesn't work.

for (i=0;i<10;i++){

$(".hi:eq(i)").css("height",n[i]);

}

Neither does this.

var i=0;
$(".hi:eq(i)").css("height",n[i]);

Something must be wrong with :eq(i).


1 Answers

This issue is that JavaScript doesn't have string interpolation.

But do it like this instead...

$(".hi").slice(0,10)
        .css('height', function(i) { 
            return n[i]; 
        });

This is far more efficient than repeating your DOM selection with a non-standard selector.

  • .slice(0,10) will give you the first 10 elements

  • .css() with a function passed as the second argument will assign the return value to the height css property of the current element in the iteration. The index of the current iteration is represented by the i parameter.

like image 83
2 revsuser1106925 Avatar answered Jul 04 '26 08:07

2 revsuser1106925



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!