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:
-
if(document.getElementById("someElement").style.display=="none"){
-
//…do something
-
}
… 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:
-
function displayNoneSet(element){
-
if(element.parentNode == null){
-
//we’ve reached the top of the tree #document doesn’t have a style property
-
//this means that no element is set to hidden on the tree from the original element sent
-
return false;
-
}else{
-
if(element.style.display == "none"){
-
///We’ve found a node that is hidden
-
return true;
-
}else{
-
//check the element’s parent, I don’t like recursion, but the only way I see this working
-
return displayNoneSet(element.parentNode);
-
}
-
}
-
}
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: Javascript, DOM, style, display, code
Popularity: 57% [?]
December 7th, 2006 at 8:37 pm
don’t like recursion? how about this?
function isVisible(elem)
{
while(elem)
{
if(elem.style.display == ‘none’)
return false;
elem = elem.parentElement;
}
return true;
}
December 8th, 2006 at 8:48 am
Thanks for the reply, I came to a similar solution as well. I posted it a couple days ago.
May 23rd, 2008 at 2:00 pm
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;
}