2

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

1

3 Answers 3

6

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.

10
  • How do you mean, with storage?
    – BASILIO
    Commented Jan 19, 2013 at 15:54
  • That's smart and I like the idea, but I don't see how it's possible to keep a precise z-index variable without iterating the DOM. The OP said he's creating some dynamic elements but we don't know how many there are before the first added element... Commented Jan 19, 2013 at 15:57
  • @BASILIO: The same mechanism you use for z-Index++ when dynamically creating the elements
    – Bergi
    Commented Jan 19, 2013 at 15:58
  • but I don't see how it's possible to keep a precise z-index ...by setting it?
    – Popnoodles
    Commented Jan 19, 2013 at 15:58
  • 1
    @BASILIO: That's a lot of program logic. Do not rely on DOM-CSS-values for that, but build a data model for it. You should have a stack (array) of your windows, for example, which you just need to pop() to get and close the topmost window.
    – Bergi
    Commented Jan 19, 2013 at 16:08
1

http://jsfiddle.net/h4ets/

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

0

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);
});
1
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
    – frobinsonj
    Commented Jun 25, 2019 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.