[ACCEPTED]-How to find the highest z-index using jQuery-z-index

Accepted answer
Score: 35

Note that z-index only affects positioned 10 elements. Therefore, any element with position: static will 9 not have a z-index, even if you assign it 8 a value. This is especially true in browsers 7 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 6 like that when used with an option that 5 returns one value will merely return the 4 first So your result is simply the z-index 3 of the first div that jQuery grabs. To grab 2 only the divs you want, use a class on them. If 1 you want all divs, stick with div.

Score: 13

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 1 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();
Score: 12

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

$.topZIndex("div");
Score: 6

Try this :

var index_highest = 0;
$('div').each(function(){
    var index_current = parseInt($(this).css("z-index"), 10);
    if(index_current > index_highest) {
        index_highest = index_current;
    }
}); 

0

Score: 3

This would do it:

$(document).ready(function() {
    var array = [];
    $("div").each(function() {
        array.push($(this).css("z-index"));
    });
    var index_highest = Math.max.apply(Math, array);
    alert(index_highest);
});

Try this

0

Score: 3

This is taken directly from jquery-ui, it 1 works really well:

(function ($) {
  $.fn.zIndex = function (zIndex) {
      if (zIndex !== undefined) {
        return this.css("zIndex", zIndex);
      }

      if (this.length) {
        var elem = $(this[ 0 ]), position, value;
        while (elem.length && elem[ 0 ] !== document) {
          // Ignore z-index if position is set to a value where z-index is ignored by the browser
          // This makes behavior of this function consistent across browsers
          // WebKit always returns auto if the element is positioned
          position = elem.css("position");
          if (position === "absolute" || position === "relative" || position === "fixed") {
            // IE returns 0 when zIndex is not specified
            // other browsers return a string
            // we ignore the case of nested elements with an explicit value of 0
            // <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
            value = parseInt(elem.css("zIndex"), 10);
            if (!isNaN(value) && value !== 0) {
              return value;
            }
          }
          elem = elem.parent();
        }
      }

      return 0;
    }
})(jQuery);
Score: 2

I don't know how efficient this is, but 4 you can use $.map to get all the z-indices:

var $divs = $('div'),
    mapper = function (elem) {
        return parseFloat($(elem).css('zIndex'));
    },
    indices = $.map($divs, mapper);

The 3 indices variable is now an array of all the z-indices 2 for all the divs. All you'd have to do now 1 is apply them to Math.max:

var highest = Math.max.apply(whatevs, indices);
Score: 1

Here how I got both lowest/highest z-indexes. If 9 you only want to get the highest z-index 8 and nothing more, then this function may 7 not efficient, but if you want to get all 6 z-indexes and the ids associated with it 5 (i.e. for use with bring 'layer' to front/send 4 to back, bring forward, send backward, etc), this 3 is one way to do it. The function returns 2 an array of objects containing ids and their 1 z-indexes.

function getZindex (id) {

     var _l = [];
     $(id).each(function (e) {
         // skip if z-index isn't set 
         if ( $(this).css('z-index') == 'auto' ) {
              return true
         }
         _l.push({ id: $(this), zindex: $(this).css('z-index') });
     });
     _l.sort(function(a, b) { return a.zindex - b.zindex });
     return _l;
}

// You'll need to add a class 'layer' to each of your layer
var _zindexes = getZindex('.layer');
var _length = _zindexes.length;

// Highest z-index is simply the last element in the array
var _highest = _zindexes[_length - 1].zindex

// Lowest z-index is simply the first element in the array
var _lowest = _zindex[0].zindex;

alert(_highest);
alert(_lowest);
Score: 0

Vanilla JS, not 100% cross-browser. Including 2 as reference for future readers/alternative 1 method.

function getHighIndex (selector) {
    // No granularity by default; look at everything
    if (!selector) { selector = '*' };

    var elements = document.querySelectorAll(selector) ||
                   oXmlDom.documentElement.selectNodes(selector),
        i = 0,
        e, s,
        max = elements.length,
        found = [];

    for (; i < max; i += 1) {
        e = window.getComputedStyle(elements[i], null).zIndex || elements[i].currentStyle.zIndex;
        s = window.getComputedStyle(elements[i], null).position || elements[i].currentStyle.position;

        // Statically positioned elements are not affected by zIndex
        if (e && s !== "static") {
          found.push(parseInt(e, 10));
        }
    }

    return found.length ? Math.max.apply(null, found) : 0;
}

More Related questions