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.
Z Index ( z-index ) is a CSS property that defines the order of overlapping HTML elements. Elements with a higher index will be placed on top of elements with a lower index. Note: Z index only works on positioned elements ( position:absolute , position:relative , or position:fixed ).
Yes: use position:relative; z-index:10 . z-index has no effect for position:static (the default).
The z-index CSS property sets the z-order of a positioned element and its descendants or flex items. Overlapping elements with a larger z-index cover those with a smaller one.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With