0

Possible Duplicate:
Select DIV with highest z-index

How to get the highest z-index value?
put the all div z-index value into array and use math.max? or any suggestion?

<div class="a" z-index="1">
<div class="a" z-index="3">
<div class="a" z-index="4">
<div class="a" z-index="5">
<div class="a" z-index="6">
<div class="a" z-index="11">...

<div class="b" z-index="//top+1">

js

var top = // highest z-index value;
Community
  • 1
  • 1
user1775888
  • 3,147
  • 13
  • 45
  • 65

5 Answers5

3

you could do:

var zIndx = [];
$("div.a").each(function() {
    zIndx.push( $(this).attr("z-index") );
});
console.log( Math.max.apply( Math, zIndx ) );
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
2

JavaScript's Array.reduce can do the job. .get can get you the array you need:

var top = $(".a").get().reduce(function (a, b) {
   return Math.max(typeof a === 'object' && $(a).attr('z-index') || a,
      $(b).attr('z-index'));
});

http://jsfiddle.net/8jpea/1/

By the way, be careful about using your own self-defined attributes. Go with data-z-index if you can.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
2
var maxValue = Math.max.apply( Math, $('.a').map(function() {
    return +$.attr(this, 'z-index');
}));

Here's the fiddle: http://jsfiddle.net/ZFhzu/


If you're using modern JavaScript, you don't need that fancy apply. You can spread the values instead:

let maxValue = Math.max(...$('.a').get().map(el => +$.attr(el, 'z-index')));

Here's the fiddle: http://jsfiddle.net/7y3sxgbk/

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • can you please explain the code? – yossi Jan 20 '19 at 09:55
  • The [`.map()`](https://api.jquery.com/jQuery.map/) function takes a function that will be called for each element in the jQuery collection, returning a new array with all the values that were returned by the function. The [`.apply()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) function lets you pass a bunch of arguments to the underlying function as an array instead. – Joseph Silber Jan 20 '19 at 18:21
1

Here's the function you can use.

var index_highest = 0;   

// more effective to have a class for the div you want to search and 
// pass that to your selector

$(".a").each(function() {

         // always use a radix when using parseInt

         var index_current = parseInt($(this).css("zIndex"), 10);

         if(index_current > index_highest) {
               index_highest = index_current;
          }
});

console.log(index_highest);
Hary
  • 5,690
  • 7
  • 42
  • 79
1
    var top = 0;
    $('.a').each(function(){
        if(top < parseInt($(this).attr('z-index'))){
            top= parseInt($(this).attr('z-index'));
        }
    });
    $('.b').attr('z-index',top+1);

jsfiddle.net/EC36x

Joseph Caracuel
  • 974
  • 1
  • 8
  • 15