I have a number of div elements with different z-index. And I want to find the highest z-index among these divs - how can I achieve it?
CSS:
#layer-1
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();
Here how I got both lowest/highest z-indexes. If you only want to get the highest z-index and nothing more, then this function may not efficient, but if you want to get all z-indexes and the ids associated with it (i.e. for use with bring 'layer' to front/send to back, bring forward, send backward, etc), this is one way to do it. The function returns an array of objects containing ids and their 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);
Vanilla JS, not 100% cross-browser. Including as reference for future readers/alternative 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;
}
Besides @justkt's native solution above, there is a nice plugin to do what you want. Take a look at TopZIndex.
$.topZIndex("div");
I don't know how efficient this is, but 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 indices
variable is now an array of all the z-indices for all the divs. All you'd have to do now is apply them to Math.max
:
var highest = Math.max.apply(whatevs, indices);