Skip to content Skip to sidebar Skip to footer

Non-jquery Equivalent Of :visible In Javascript?

So jQuery provides this awesome pseudo to query in DOM on ':visible', unfortunately, its rather heavily tied into the core of jQuery and Sizzle (or whatever engine you may use). I

Solution 1:

You can get the relevant code from the the source code:

jQuery.expr.filters.hidden = function( elem ) {
    var width = elem.offsetWidth,
        height = elem.offsetHeight;

    return ( width === 0 && height === 0 ) ||
           (!jQuery.support.reliableHiddenOffsets &&
           ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
  • jQuery.css can be replaced with getComputedStyle (or .currentStyle for IE).
  • jQuery.support.reliableHiddenOffsets is a variable which determines whether the properties are reliable (IE8-).

Solution 2:

I just look at jquery first as it is JavaScript. Here is the actual code:

if ( jQuery.expr && jQuery.expr.filters ) {

    // here is the real guts of it
    jQuery.expr.filters.hidden = function( elem ) {

        // plain old JavaScript determining offsetvar width = elem.offsetWidth,
        height = elem.offsetHeight;

        // if any of these are "true" then its "invisible"return ( width === 0 && height === 0 ) || 
        (!jQuery.support.reliableHiddenOffsets && 
        ((elem.style && elem.style.display) || 
        jQuery.css( elem, "display" )) === "none");
    };

    // this is just checking for not hidden
    jQuery.expr.filters.visible = function( elem ) {
        return !jQuery.expr.filters.hidden( elem );
    };
}

The "reliableHiddenOffsets" code is defined way before this and you can see it below

isSupported = ( tds[ 0 ].offsetHeight === 0 );

tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";

// Check if empty table cells still have offsetWidth/Height// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );

The real lesson here is this stuff is not rocket science. Crack open jQuery and take a look. The real gem of jQuery is its been tested and banged on so hard that you will probably not find any issues with it. That's worth so much besides the great selector engine and abstraction. Don't be afraid to actually look. You will learn something in the process as a nice side effect.

Solution 3:

I'd recommend you use at the very least some selector library that does this work for you. Otherwise you're just wasting your effort in something that has already been tested and proven successful for no particular reason, and you're bound to probably even get it wrong the first few attempts you make.

For instance Sizzle is only 4kb when minified/gzipped so I see virtually no reason not to use it.

Post a Comment for "Non-jquery Equivalent Of :visible In Javascript?"