Can querySelectorAll return only visible elements?
Answers:
The
querySelectorAllmethod 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
querySelectorAllwith 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 elementsIn this example:
- The
offsetWidthandoffsetHeightproperties are used to check if the element has a size (is not hidden bydisplay: none). - The
getComputedStylefunction checks if the element's visibility is not set tohidden.
You can replace
'your-selector-here'with your actual selector to filter relevant visible elements.- The