z-index of an element without defined position

6

Is it possible to know z-index of an element without a defined position using javascript?

For example in this code:

CSS

#exemplo1 {
    z-index:4;
}
#exemplo2 {
    z-index:4;
    position: relative;
}

HTML

<div id="exemplo1"></div>
<div id="exemplo2"></div>

Is it possible to get z-index of exemplo1 , in this case 4 , even though position is not defined?

What I tested:

var e1 = document.getElementById('exemplo1');
var e2 = document.getElementById('exemplo2');
console.log(e1.style.zIndex); // nada
console.log(e2.style.zIndex); // nada
console.log(window.getComputedStyle(e1).getPropertyValue("z-index")); // auto no Chrome, 4 no IE11 e FF
console.log(window.getComputedStyle(e2).getPropertyValue("z-index")); // 4

jsFiddle

    
asked by anonymous 24.03.2014 / 21:58

1 answer

2

My only suggestion is to momentarily change the position of your element to relative , observe z-index , and then return to what it was before:

var pos = e1.style.position;
e1.style.position = "relative";
console.log(window.getComputedStyle(e1).getPropertyValue("z-index"));
e1.style.position = pos;

Example . Since JavaScript execution on the main page is synchronous , this will not cause any visual glitch.

    
24.03.2014 / 22:12