Excellent observation. You're correct that elementFromPoint() returns the parent element even when a pseudo-element covers the point, which might seem counterintuitive.
This happens because pseudo-elements are not actual DOM nodes, but rendering artifacts created by CSS. They are visually rendered on top of their parent element but do not exist in the DOM tree.
To definitively detect if a pseudo-element covers a point, you'll need a more comprehensive approach:
javascript
function getElementAtPoint(x, y) {
const element = document.elementFromPoint(x, y);
// Check ::before and ::after pseudo-elements
const pseudos = ['::before', '::after'];
for (const pseudo of pseudos) {
const pseudoStyle = window.getComputedStyle(element, pseudo);
// Check if pseudo-element exists and has content
if (pseudoStyle.content !== 'none') {
const elementRect = element.getBoundingClientRect();
const pseudoRect = {
top: elementRect.top + parseFloat(pseudoStyle.top || 0),
left: elementRect.left + parseFloat(pseudoStyle.left || 0),
width: parseFloat(pseudoStyle.width || elementRect.width),
height: parseFloat(pseudoStyle.height || elementRect.height)
};
// Check if point is within pseudo-element's calculated bounds
if (
x >= pseudoRect.left &&
x < pseudoRect.left + pseudoRect.width &&
y >= pseudoRect.top &&
y < pseudoRect.top + pseudoRect.height
) {
return {
element,
pseudoElement: pseudo
};
}
}
}
return { element, pseudoElement: null };
}
Key improvements in this approach:
Explicitly calculates pseudo-element bounds
Checks content and positioning
Returns both the element and pseudo-element (if applicable)
Handles cases where pseudo-element might partially or fully cover the point
Example usage:
javascript
const result = getElementAtPoint(100, 200);
console.log(result.element); // The DOM element
console.log(result.pseudoElement); // '::before', '::after', or null
This method provides a more robust way to determine what's visually at a specific point, accounting for both DOM elements and their pseudo-elements.