How to find the highest z-index using jQuery

Solution 1:

Note that z-index only affects positioned elements. Therefore, any element with position: static will not have a z-index, even if you assign it a value. This is especially true in browsers like Google Chrome.

var index_highest = 0;   
// more effective to have a class for the div you want to search and 
// pass that to your selector
$("#layer-1,#layer-2,#layer-3,#layer-4").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;
    }
});

JSFiddle demo

A general jQuery selector like that when used with an option that returns one value will merely return the first So your result is simply the z-index of the first div that jQuery grabs. To grab only the divs you want, use a class on them. If you want all divs, stick with div.

Solution 2:

Here is a very concise method:

var getMaxZ = function(selector){
    return Math.max.apply(null, $(selector).map(function(){
        var z;
        return isNaN(z = parseInt($(this).css("z-index"), 10)) ? 0 : z;
    }));
};

Usage:

getMaxZ($("#layer-1,#layer-2,#layer-3,#layer-4"));

Or, as a jQuery extension:

jQuery.fn.extend({
    getMaxZ : function(){
        return Math.max.apply(null, jQuery(this).map(function(){
            var z;
            return isNaN(z = parseInt(jQuery(this).css("z-index"), 10)) ? 0 : z;
        }));
    }
});

Usage:

$("#layer-1,#layer-2,#layer-3,#layer-4").getMaxZ();

Solution 3:

Besides @justkt's native solution above, there is a nice plugin to do what you want. Take a look at TopZIndex.

$.topZIndex("div");