Reputation: 61
I need to find top most div by checking z-index:
<div>
<div id="box_1">some image</div>
<div id="box_444">some image</div>
<div id="box_555">some image</div>
<div id="box_888">some image</div>
<div id="box_999">some image</div>
</div>
the best way I can explain is like shuffling a deck of images in the dark without knowing which image is on top. Basically I need to check which div has the highest z-index and identify by the div's id.
Can any jquery expert help me out?
Thanks.
Upvotes: 1
Views: 2546
Reputation: 71939
Basically I need to check which div has the highest z-index and identify by the div's id
Are you looking for something like this?
var allDivs = $('div div');
var topZindex = 0;
var topDivId;
allDivs.each(function(){
var currentZindex = parseInt($(this).css('z-index'), 10);
if(currentZindex > topZindex) {
topZindex = currentZindex;
topDivId = this.id;
}
});
console.log(topDivId);
console.log(topZindex);
Upvotes: 3
Reputation: 18233
$.fn.topmost = function () {
var positionedDivs = this.filter( function() {
return !isNaN( parseInt( $(this).css("z-index"), 10 ) );
});
var topElem = positionedDivs.first();
positionedDivs.each( function() {
if ( $(this).css('z-index') > +topElem.css("z-index") ) {
topElem = $(this);
}
});
return topElem.get(0) || this.get(0);
};
$(function() {
var topDiv = $('div > div').topmost();
console.log( topDiv.id )
});
Upvotes: 1
Reputation: 29831
This will get you there:
$(function(){
var highest = -1, el = null;
$('div[id^="box"]').each(function(){
var z = parseInt($(this).css('z-index'), 10);
if (z > highest) {
el = this;
highest = z;
}
});
console.log('the highest is:', el)
});
Upvotes: 1
Reputation: 55750
Try this
$(function() {
var $divs = $('div > div');
var maxId = '';
var max = 0;
$.each($divs, function(i){
var a = $($divs[i]).css('z-index');
console.log(a);
if(parseInt(a) > parseInt(max)){
max = a;
maxId = $(this).attr('id');
}
});
alert(maxId);
});
Upvotes: 1
Reputation: 15111
Try this
var greatest = 0;
var greatestDiv;
$('div').each(function(){
if($(this).css('z-index') > greatest){
greatest = $(this).css('z-index');
greatestDiv = $(this).attr('id');
}
})
console.log(greatest);
console.log(greatestDiv);
Upvotes: 1