JSFiddle - React, Tailwind, and code Playground
HTML
<div id='a'>A</div>
<div id='b'>B</div>
<div id='c'>C</div>
<br/><br/><br/>
<button>Click here</button><br/>
<p>Current greatest z-index: <span id='z'></span></p>
CSS
#a {
z-index: 1;
position: absolute;
background-color: red;
}
#b {
z-index: 2;
position: absolute;
background-color: green;
}
#c {
z-index: auto;
position: absolute;
background-color: blue;
}
JavaScript
$("button").click(function(){
var newZ = parseInt(getTopElement($("div")).css("z-index"), 10);
$("div").each(function(){
if (isNaN(parseInt($(this).css("z-index"),10))){
$(this).css("z-index", ++newZ);
alert ("Element " + $(this).attr("id") + " has been given a z-index of " + newZ);
}
});
$("#z").text(getTopElement($("div")).css("z-index"));
});
$("#z").text(getTopElement($("div")).css("z-index"));
function getTopElement(elems){
// Store the greates z-index that has been seen so far
var maxZ = 0;
// Stores a reference to the element that has the greatest z-index so far
var maxElem;
elems.each(function(){
var z = parseInt($(this).css("z-index"), 10);
// Ignore z-index of auto
if (!isNaN(z)){
if (parseInt($(this).css("z-index"), 10) > maxZ) {
maxElem = $(this);
maxZ = parseInt($(this).css("z-index"), 10);
}
}
});
return maxElem;
};