ruk·si

🍦 JavaScript
Screen Position

Updated at 2015-09-30 01:48

It's sometimes useful to get full DOM element stack in a specific pixel position when debugging elements that are not in the general document flow because of e.g., relative positioning.

I found this useful when debugging SVG based charts with thousands of elements.

var elementScanner = function (e) {
    var elements = [];
    var mouseX = e.pageX;
    var mouseY = e.pageY;
    var mouseViewportX = mouseX - window.pageXOffset;
    var mouseViewportY = mouseY - window.pageYOffset
    var el = document.elementFromPoint(mouseViewportX, mouseViewportY);
    if (!el) return;

    while (el && el.tagName != "BODY" && el.tagName != "HTML") {
        elements.push(el);
        el.style.display = "none";
        el = document.elementFromPoint(mouseViewportX, mouseViewportY);
    }

    i = elements.length - 1;
    while (i > -1) {
        elements[i].style.display = "";
        i--;
    }

    console.log(elements);
};
document.addEventListener('click', elementScanner, false);