return elements that match specified CSS selector(s)

Can querySelectorAll return only visible elements?

Answers:

  • The querySelectorAll method itself does not filter results based on visibility; it selects all elements that match the specified CSS selector(s) regardless of their visibility state (e.g., display: none, visibility: hidden, etc.).

    However, you can combine querySelectorAll with additional JavaScript to filter out the visible elements. Here's how you can do it:

    // Select all elements that match a given selector
    let elements = document.querySelectorAll('your-selector-here');
    
    // Filter to include only visible elements
    let visibleElements = Array.from(elements).filter(element => {
        return element.offsetWidth > 0 && element.offsetHeight > 0 && getComputedStyle(element).visibility !== 'hidden';
    });
    
    // visibleElements now contains only the visible elements
    

    In this example:

    • The offsetWidth and offsetHeight properties are used to check if the element has a size (is not hidden by display: none).
    • The getComputedStyle function checks if the element's visibility is not set to hidden.

    You can replace 'your-selector-here' with your actual selector to filter relevant visible elements.