How to find the highest z-index within a document no matter what tags they are?
Asked Answered
J

3

7

How can I find the highest z-index within a document no matter what tags they are?

I found this code but I tested it and it does not work,

//include jQuery.js --  visit: http://jquery.com/
$(function(){
    var maxZ = Math.max.apply(null,$.map($('body > *'), function(e,n){
           if($(e).css('position')=='absolute')
                return parseInt($(e).css('z-index'))||1 ;
           })
    );
    alert(maxZ);
});

Any better approach to do this?

EDIT:

It seems to work if I change the code to this,

$('body *')

$('body > *') --> is for div only I guess.
Jonjona answered 16/7, 2013 at 20:40 Comment(1)
great question man! I always like to understand the code rather than resort to plugins first.Salinger
B
6

This isn't the most efficient solution, but it should work. jsFiddle.

Please note you have to have a position specified in order for the z-index to return a value.

var highest = -999;

$("*").each(function() {
    var current = parseInt($(this).css("z-index"), 10);
    if(current && highest < current) highest = current;
});

alert(highest);
Boehmer answered 16/7, 2013 at 20:57 Comment(1)
It's good practice to use Number.NEGATIVE_INFINITY or -Infinity instead of the magic number -999. If all elements are positioned and all have z-index of less than -999, then this will not give the correct answer.Dichasium
S
3

This seems to work:

var maxZ=0;
$('*').each(function(){
    if($(this).css('zIndex') > maxZ) maxZ = $(this).css('zIndex');
})
console.log(maxZ);

jsFiddle example

I think one of the issues with the code you posted is that you're only checking for absolutely positioned elements.

Sacristan answered 16/7, 2013 at 20:58 Comment(0)
M
2

Just to add a solution without jQuery:

const all = Array.from(document.querySelectorAll('body *'));
console.log('Found ',all.length,' elements');
const allIndexes = all.map((elem) => {
  if (elem.style) {
    return +elem.style.zIndex || 0;
  }
  return -Infinity;
});

const max = Math.max.apply(null, allIndexes);
console.log('Max z-index:', max);
.cl {
position: absolute;
border: 1px solid;
}
<div class="cl" style="z-index: 3;width:100px;height:100px;background:#A00;"></div>
<div class="cl" style="z-index: 4;width:90px;height:90px;background:#0A0;"></div>
<div class="cl" style="z-index: 5;width:50px;height:50px;background:#AA0;"></div>
<div class="cl" style="z-index: 6;width:40px;height:40px;background:#AAA"></div>
Musca answered 5/4, 2018 at 17:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.