Sobes.tech
Middle

How can all hidden elements on a page be found?

sobes.tech AI

Answer from AI

CSS selectors can be used in conjunction with JavaScript.

Main approaches:

  • ** :not(:visible) pseudo-class (non-standard)**: Although CSS does not have a direct selector for "invisible," some frameworks and libraries (e.g., jQuery) offer their own implementations or you can create custom logic. This approach is more conceptual for explanation.
  • Checking display, visibility, and opacity: This is the most reliable method in native JS. Elements with display: none, visibility: hidden, or opacity: 0 (if they are not a parent of visible children) are considered hidden.
// Get all elements on the page
const allElements = document.querySelectorAll('*');

const hiddenElements = [];

allElements.forEach(element => {
  const computedStyle = getComputedStyle(element);

  // Check display: none
  if (computedStyle.display === 'none') {
    hiddenElements.push(element);
    return; // Element is hidden, no need to check visibility and opacity further
  }

  // Check visibility: hidden
  if (computedStyle.visibility === 'hidden') {
    hiddenElements.push(element);
    return;
  }

  // Check opacity: 0
  if (computedStyle.opacity === '0' && !(element.children.length > 0 && Array.from(element.children).some(child => getComputedStyle(child).opacity !== '0')) ) {
    // Complex condition for opacity: check that the element itself is invisible due to opacity: 0
    // and that it has no visible children (with opacity > 0)
    hiddenElements.push(element);
    return;
  }

  // Additional check for hiding by parent element (more complex scenario)
  let parent = element.parentElement;
  while (parent) {
    const parentComputedStyle = getComputedStyle(parent);
    if (parentComputedStyle.display === 'none' || parentComputedStyle.visibility === 'hidden' || parentComputedStyle.opacity === '0') {
      hiddenElements.push(element);
      break; // Element is hidden by parent
    }
    parent = parent.parentElement;
  }
});

console.log('Hidden elements:', hiddenElements);
  • jQuery: jQuery simplifies this task with its :hidden pseudo-class.
// Use jQuery to find hidden elements
const hiddenElementsJquery = $(':hidden');

console.log('Hidden elements (jQuery):', hiddenElementsJquery);

Important: When using native JavaScript, checking opacity: 0 requires careful analysis to avoid including parent elements in the hidden list if only one of their children has opacity: 0 but the parent and other children are visible. Also, consider that an element might be hidden due to size (width/height 0) or being outside the viewport, but this is not a direct CSS "hidden" property.