Pregunta

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.
¿Fue útil?

Solución

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);

Otros consejos

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.

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>

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top