Image Image Image Image Image

© Copyright 2012 ABCoder | Email | RSS

Scroll to Top

To Top

Core JavaScript tips and tricks: playing with javascript



In Core JavaScript

By Saif Uddin

A better process to find maximum z-index within a page

On 31, Jan 2009 | In Core JavaScript, JavaScript, jQuery | By Saif Uddin

Once I needed to get maximum z-index of a DIV to show message at the top of the screen.
Usually, I used arbitrary z-index of 100 of the DIV. But that one is not at the top and it’s hidden by others.
What’s wrong? And unfortunately I found that there are 3 more div-s which have z-index attribute which are greater than 100.
So I changed the z-index to 1000. This time I can see one portion of the DIV.
But 2 more elements get the desired message container DIV overlaid. Frustrating! Huh!
Trial and error method always makes you delay.
I know JavaScript or jQuery may get rid of this hell.
I made an absolute tinny code to find the highest z-index of absolute DIV
to show my shouting box and to make it appear absolutely at the top of all html elements.

//include jQuery.js --  visit:
    var maxZ = Math.max.apply(null,$.map($('body > *'), function(e,n){
                return parseInt($(e).css('z-index'))||1 ;

I used selector of ”body > *‘ instead of ‘body *‘.

body > *‘ means all tags/elements which are found at first depth of
whether ”body *‘ selects all tags/elements at any depth.
It doesn’t matter what’s is the maximum/highest z-index of an absolute element
rather it matters what’s the maximum/highest z-index of the absolute elements
which are next to in first depth only to show the shouting box on top most strata.

N.B. Shouting box is appended to document.body in this case.

Tags | , , , , , , , , , , ,


  1. highestElement.css("zIndex", $("*").length + 1);


    $("body > *").each(function(el, i) {
    if($(el).css("position") != "static" && $(el).css("z-index") >= maxZ) {
    maxZ = $(el).css("z-index");

  2. User

    I just want to note that this will not work in all cases. You need to scan the entire DOM to find the top z-index. Maybe if you control all of the HTML/CSS on the page, then you can make sure that absolute elements are directly under the body tag but if you don’t (say you are showing a third party ad), then you will need to scan the whole DOM.

    Test case:

    Test 2

  3. User

    Whoops. It killed my html. Try #2

    <div style=”background:#00f; position:absolute; top:0; left:0; z-index:50″>Test</div>
    <div><div style=”background:#f00; position:absolute; top:0; left:0; z-index:100″>Test 2</div></div>

  4. fandm


  5. A better process to find maximum z-index within a page I was recommended this website by my cousin. I’m not sure whether this post is written by him as nobody else know such detailed about my trouble. You’re incredible! Thanks! your article about A better process to find maximum z-index within a page Best Regards Lawrence Lawrence