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). Is there a good equivalent in plain JavaScript when only a given element is known?
A reminder on the jQuery :visible rules:
An ancestor element is hidden, so the element is not shown on the page.
Note: checking just style of the given element will not always work: a parent might be hidden instead hiding all children.
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-).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 offset
var 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With