Explain Codes LogoExplain Codes Logo

How can I check if an element exists in the visible DOM?

javascript
dom-manipulation
javascript-variables
visibility-checks
Anton ShumikhinbyAnton Shumikhin·Dec 23, 2024
TLDR

Confirm an element's visibility in the displayable layout with:

function isElementVisible(el) { const mysteryBox = document.querySelector(el); // our "out-of-the-blue" element if (!mysteryBox) return false; const { top, bottom, left, right } = mysteryBox.getBoundingClientRect(); return ( top < window.innerHeight && /* The riddle: It’s not buried underground */ bottom > 0 && /* Not flying high in the sky either */ left < window.innerWidth && /* Doesn't take a step to the left */ right > 0 /* ...or a jump to the right */ ); } console.log(isElementVisible('#elementId')); // It's visible! No? Well, it's just not that into you.

document.querySelector targets the element, and getBoundingClientRect calculates its vista bounds. They collaborate to affirm the element's display status, not just its mere DOM existence.

Deep dive into detection strategies

Element in the DOM?

Check an element's presence in the DOM using the likes of document.getElementById or document.querySelectorAll. But be aware, this only attests to the element's existence, not its visibility.

let elementExists = document.getElementById('elementId'); console.log(!!elementExists); // true or false, check for existence... not for invisibility cloak usage.

This can be tricky if the element's a master of hide and seek (display: none), even though it's in the DOM.

Is the element visible?

Visibility heavily relies on positions and renderings. Here's your CSS detective kit:

  • getBoundingClientRect: provides a snapshot of the element’s position in the viewport.
  • display, visibility, opacity: These CSS properties dictate its visibility.

Elements visible to users pass these tests:

  1. Resides within the viewport boundaries.
  2. Is not ghosting you with CSS (display: none or visibility: hidden).
  3. Is not a transparent entity (opacity not 0).

Keeping it cross-browser compatible

Apply document.body.contains(element) to sustain cross-browser compatibility while verifying if the parent document accommodates the element.

Variable retention after DOM removal

Variables have a knack for retaining a reference to a removed DOM node. To update this, define the variable to null manually.

let myElement = document.getElementById('myElement'); // myElement plays 'Now you see me, now you don't!' myElement = null; // Set the stage for the next act. No remnants of the previous act allowed!

Use Node.isConnected to validate an element's attachment to the DOM. Unless explicitly removed, it stays true (like a loyal friend).

Dealing with the Shadow DOM

In a scenario with Shadow DOM, use element.shadowRoot combined with node.isConnected. The Shadow DOM likes to play hide and seek, but it's less thrilling for developers.

Deeper understanding of JS variables

Read articles discussing JavaScript variables and their quirks post-DOM manipulation to unravel any confusion and aberrations.

Expanded toolkit for element visibility

Respond to dynamic changes

Invoke MutationObserver or IntersectionObserver to adapt to dynamic changes in DOM elements or their visibility.

jQuery for simplified solutions

jQuery offers user-friendly methods for visibility checks. But remember, native JavaScript often wins for performance.

The pitfalls of outdated references

Avoid skeletons in the closet (reference rigidity) by keeping in mind that JavaScript does not automatically update references after DOM alterations.