Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery :hidden selector equivalent in Javascript?

I have this code;

$('.m-shop-top-product .b-item:hidden').slice(0, 10).show();

I want to convert it into the Pure Javascript, I am not able to find equivalent Javascript code which return me all the elements which are hidden! I tried like this;

Array.from(document.querySelectorAll('.m-shop-top-product .b-item:hidden')).slice(0,10)

but it gives error as;

Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '.m-shop-top-product .b-item:hidden' is not a valid selector.
like image 373
Sam Avatar asked Jan 31 '26 03:01

Sam


1 Answers

Well, according to the jQuery docs, the hidden selector does the following:

  • They have a CSS display value of none.
  • They are form elements with type="hidden".
  • Their width and height are explicitly set to 0.
  • An ancestor element is hidden, so the element is not shown on the page.

So, you'd do a document.querySelectorAll(".m-shop-top-product .b-item") and then apply filter(e) to check css style "display", form hidden attribute, width, height, and loop through element.parentElement until you read documentElement, to see if the parent is hidden or not.

function isHidden(){ /* TODO: Implement */ return false;}

document.querySelectorAll(".m-shop-top-product .b-item").filter(function(e){
   return isHidden(e);
});

e.g.

// Where el is the DOM element you'd like to test for visibility
function isHidden(el) 
{
    var style = window.getComputedStyle(el);
    return (style.display === 'none')
}

or

function isVisible (ele) 
{
    var style = window.getComputedStyle(ele);
    return  style.width !== "0" &&
    style.height !== "0" &&
    style.opacity !== "0" &&
    style.display!=='none' &&
    style.visibility!== 'hidden';
}

or

function isVisible(el)
{
    // returns true iff el and all its ancestors are visible
    return el.style.display !== 'none' && el.style.visibility !== 'hidden'
    && (el.parentElement? isVisible(el.parentElement): true)
}

or

function isHidden(el) 
{
    if(!el)
        return false;

    do 
    {
        if(!(el instanceof Element))
            continue;

        var style = window.getComputedStyle(el);

        if (style.width == "0" || style.height == "0" || style.opacity == "0" || style.display == "none" || style.visibility == "hidden")
        {
            return true;
        }


        // console.log(el);
    } while ((el = el.parentNode));

    return false;
}
like image 143
Stefan Steiger Avatar answered Feb 02 '26 17:02

Stefan Steiger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!