Skip to content

Instantly share code, notes, and snippets.

@johntron
Last active December 3, 2024 04:22
Show Gist options
  • Select an option

  • Save johntron/fe4ca34ac5cf52e93ce4227775a00cee to your computer and use it in GitHub Desktop.

Select an option

Save johntron/fe4ca34ac5cf52e93ce4227775a00cee to your computer and use it in GitHub Desktop.
Find elements partially contained within rect
// overlay is the rect within which we're trying to find elements
let overlay = document.createElement('div');
overlay.setAttribute('style', `position: absolute; left: 100px; top: 100px; width: 500px; height: 100px; backdrop-filter: invert(100%); z-index: 1000`)
document.body.insertBefore(overlay, document.body.children[0]);
let overlayRect = overlay.getBoundingClientRect()
const containedElements = []
for (element of Array.from(document.body.querySelectorAll(':not(script):not(iframe)'))) {
// get bounds of candidate element
const bounds = element.getBoundingClientRect()
// determine which coordinates fall within overlay's values
const leftIn = overlayRect.left < bounds.left && bounds.left < overlayRect.right;
const rightIn = overlayRect.left < bounds.right && bounds.right < overlayRect.right;
const topIn = overlayRect.top < bounds.top && bounds.top < overlayRect.bottom;
const bottomIn = overlayRect.top < bounds.bottom && bounds.bottom < overlayRect.bottom;
// constrain matches to two dimensions (x and y; left/right and top/bottom)
if (leftIn && topIn || rightIn && topIn || leftIn && bottomIn || rightIn && bottomIn) {
containedElements.push(element)
}
}
// from containedElements, calculate the highest-level elements (ones not contained within other elements in the list)
let independent = []
for (a of containedElements) {
if (containedElements.every((b) => a === b || !b.contains(a))) {
independent.push(a)
}
}
console.log(independent)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment