Invisible if css is enabled, don't click

Javascript: determine if element (or any of it’s parents) is hidden.

I ran into a problem building a webapp today, I needed a way to determine if a specific element is hidden. Most of the time you can just check it’s style display:

  1. if(document.getElementById("someElement").style.display=="none"){
  2. //…do something
  3. }

… but what happens when it’s parent (or parents parent, or parents parents parent, ad nauseum ad infinitum) is hidden? There is no way (I could tell anyways) to tell if an element is hidden as a result of a parent node somewhere being hidden. Someone had suggested that .offsetParent was set to null in Firefox if the element was hidden, it worked, initially. I found out however this doesn’t work in Internet Explorer and even in Firefox elements such as Select never have an offsetParent. So back to the drawing board, and what I came up with was what I originally had thought would be the solution I’d have to use. The reason I didn’t initially develop it was because it uses recursion, I don’t like recursion, it’s inefficient and looks sloppy but without a better solution I came up with the following:

  1. function displayNoneSet(element){
  2. if(element.parentNode == null){
  3. //we’ve reached the top of the tree #document doesn’t have a style property
  4. //this means that no element is set to hidden on the tree from the original element sent
  5. return false;
  6. }else{
  7. if(element.style.display == "none"){
  8. ///We’ve found a node that is hidden
  9. return true;
  10. }else{
  11. //check the element’s parent, I don’t like recursion, but the only way I see this working
  12. return displayNoneSet(element.parentNode);
  13. }
  14. }
  15. }

And there it is in all it’s simplistic glory, if anyone reading has a better solution, I would like to hear it.

Technorati Tags: , , , ,

Popularity: 57% [?]

Related Posts

3 Responses to “Javascript: determine if element (or any of it’s parents) is hidden.”

  1. gcage Says:

    don’t like recursion? how about this?

    function isVisible(elem)
    {
    while(elem)
    {
    if(elem.style.display == ‘none’)
    return false;
    elem = elem.parentElement;
    }

    return true;
    }

  2. Jared McAteer Says:

    Thanks for the reply, I came to a similar solution as well. I posted it a couple days ago.

  3. Jason K Says:

    Since trying to focus on an element that’s hidden gives you an error (the same error if you try to focus on a disabled input element) you could try this:

    function isElementHidden(field) {
    try {
    field.focus();
    } catch() {
    if (field.disabled) {
    field.disabled = false;
    returnVal = isElementHidden(field);
    field.disabled = true;
    return returnVal;
    } else {
    return true;
    }
    }
    return false;
    }

Leave a Reply

We did not invent the algorithm. The algorithm killed Jeeves. The algorithm constantly finds Jesus. This is not the algorithm. This is close.