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
This is taken directly from jquery-ui, it 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);
If you are doing what I think you're doing, there is no need. Just do this:
$('div[id^=layer-]').css('z-index', 0);
$(this).css('z-index', 1000);
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
Try my fiddle:
http://planitize.tumblr.com/post/23541747264/get-highest-z-index-with-descendants-included
This combines three advantages I haven't seen combined elsewhere:
One disadvantage: no cross-browser guarantees.
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;
}
});
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
.