Owzzz
Owzzz

Reputation: 177

Looping through a collection of li elements adding a z-index and incrementing value on each

I'm trying to do what I thought would be a simple task of checking a content slider div looking for the li elements, and adding a z-index to to each one, incrementing the value by one each time.

So for a collection of three li elements they would be assigned:

<li style="z-index:1"></li> <li style="z-index:2"></li> <li style="z-index:3"></li>

I have tried doing this by using the following code:

  var $lis = $('#contentSlider ul li');

                  for(var i = 0; i < $lis.length; ++i){

                      $lis:eq(1).css('z-index',1);              
                  }

And also tried using:

var $lis = $('#contentSlider ul li');

                  for(var i = 0; i < $lis.length; ++i){


                    $('li').index($lis); 

                  }

Any idea how would be best to do this?

Upvotes: 0

Views: 1277

Answers (2)

Khoa Nguyen
Khoa Nguyen

Reputation: 1317

You can do simply like this

$('#contentSlider li').each(function(index) {
    $(this).css('z-index', index);
});

Demo: http://jsfiddle.net/ynhat/zgYWK/

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237975

You need the each method:

$('#contentSlider ul li').each(function(i, el) {
    $(el).css('z-index', i + 1);
});

You supply a function to the each method. This function is run once for each element in the selection. Each time it is called, it is passed the element's position in the selection (the index) as the first argument and the element itself as the second argument. We need to add 1 to i because it is 0-indexed.

Upvotes: 1

Related Questions