Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment z-index for each div

I am working on a design where divs overlay each other and I do to separately increment z-index by 1 for each member of a class. And I feel like there is a better way to do it with jquery.

What I want is something like for each div with the class section to have a z-index greater by than the previous but not being thrown off by divs which are not members of the specific class such as

<div class="section" style="z-index:1">Lorem</div>
<div class="section" style="z-index:2">Lorem</div>
<div id="OutOfPlaceDiv">Foo</div>
<div class="section" style="z-index:3">Lorem</div>
like image 347
Slava Knyazev Avatar asked Feb 01 '26 22:02

Slava Knyazev


1 Answers

Use the each method to iterate through the elements with that class.

$('.section').each(function(index) {
  $(this).css("z-index", index);
});

This will set the indexes to 0, 1, 2 etc. If you want to start at something other than 0:

var offset = 1;
$('.section').each(function(index) {
  $(this).css("z-index", offset + index);
});
like image 102
dursk Avatar answered Feb 04 '26 11:02

dursk