Javascript: determine if element (or any of it’s parents) is hidden. Pt. 2 (a better solution)
I while ago I posted my code to find out if an element is hidden (with added complexity that if it’s parent is hidden it will also be hidden despite the fact that it’s own display style may not be set.) Originally I came up with the following code:
-
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);
-
}
-
}
Right away I knew it was a less than perfect example of finding what I needed, I prefer to avoid recursion as much as possible. Eventually I came to the realization that I was overthinking the problem and I came up with a much more elegant solution to the problem. And here it is:
-
function displayNoneSet(element){
-
while(element.parentNode){
-
if(element.style.display=="none"){
-
//if we have found an element on the DOM tree that is not displayed
-
return true;
-
}
-
element=element.parentNode;
-
}
-
//if we’ve got to this point no element was found that had style.display set
-
return false;
-
}
This I can live with much easier.
Technorati Tags: javascript, dom, style, display, element
Popularity: 48% [?]