Search code examples
jqueryz-indexjquery-1.9

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


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.

Solution

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