Wednesday, May 20, 2015

Checking if Elements are Hidden Using Javascript

According to stackoverflow.com, Selenium WebDriver has 9 checks to verify whether an element is hidden or not.

1.  OPTION, OPTGROUP (iff enclosing select is hidden)
2.  IMAGEMAP (iff image is hidden)
3.  INPUT (iff type is hidden)

    if((element.tagName.toLowerCase() == "input") && (element.type.toLowerCase() == "hidden")) {
        return true;
    }

4. NOSCRIPT (always hidden)

    if(element.tagName.toLowerCase() == "noscript") {
        return true;
    }

5. Visibility (iff value is hidden)

    if(element.style.visibility == 'hidden') {
        return true;
    }

6.  Display (iff value is none or has ancestor)

    if(findFirstAncestorByDisplayNone(element) != null) {
        return true;
    }

function findFirstAncestorByDisplayNone(element) {
    while(element != null){
        if(element.style.display == 'none') {
            return element;
        }
        element = element.parentElement;
    }
    return element;
}

7.  Transparency/Opacity (iff value is 0)

    if(element.style.opacity == 0) {
        return true;
    }

8.  Hidden (iff value is true or has ancestor)
Note: variation for IE, see stackoverflow.com.

    if(findFirstAncestorByHidden(element) != null) {
        return true;
    }

function findFirstAncestorByHidden(element) {
    while(element != null){
        if(element.hidden == true) {
            return element;
        }
        element = element.parentElement;
    }
    return element;
}

9.  Size (iff enclosing box is 0 by 0)
Note: variation positive size, see stackoverflow.com.

    if(element.offsetWidth == 0 && element.offsetHeight == 0) {
        return true;
    }

10.  Overflow

    if(element.style.overflow == 'hidden') {
        return true;
    }

For step 9, there are many variations for checking height and width.  Let me do a quick and dirty overview.  See stackoverflow.com for more on this.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight - Includes border
    element.offsetWidth
    element.offsetHeight;

//https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight
    element.clientWidth;
    element.clientHeight;

// More precise, non integer value
    element.getBoundingClientRect().right - element.getBoundingClientRect().left;
    element.getBoundingClientRect().top - element.getBoundingClientRect().bottom;

// Additional style, depending on certain circumstances, will roll into offset
    element.width;
    element.height;

// Additional style, depending on certain circumstances, will roll into offset
    element.style.width;
    element.style.height;

// For scroll bar
    element.scrollWidth;
    element.scrollHeight;"