Reputation: 887
I have a lot of dynamic created elements, anytime it getting z-Index++, so that the latest element is anytime on top. When one other of them will be clicked, he get his z-Index max+1. So i need to get the element, that is on top, how can i do it?
Native JS Only please. Thank you
Upvotes: 2
Views: 3304
Reputation: 195
This a best solution
$(function(){
var maxZ = Math.max.apply(null,$.map($('body > *'), function(e,n){
if($(e).css('position')=='absolute')
return parseInt($(e).css('z-index'))||1 ;
})
);
alert(maxZ);
});
Upvotes: 0
Reputation: 3393
assuming you are only applying z-index in the style attribute
var elems = document.body.getElementsByTagName("*");
var largest;
var check = 0;
for(i=0;i<elems.length;i++){
if(elems[i].style.zIndex > check){
check = elems[i].style.zIndex;
largest = elems[i];
}
}
// largest is the element
// check is the z-index value of the element with largest z-index
getting the computed style of elements seems to be an issue in webkit browsers such as chrome, and safari as it returns auto, this is a major isssue as chrome especially now is a popular and widely used browser. so for now i would suggest if you want to do this apply the z-index in a style attribute until the bug is fixed
Upvotes: 1
Reputation: 664970
Don't try to find it - you would need to iterate all your DOM. As you are creating them dynamically, just save a reference to it and update it each time. Or just store the current highest z-index
value in a max
variable.
Upvotes: 6