Debug DOM elements overlapped from CSS positioning

· forensicks's blog


Find yourself trying to figure out which elements are improperly obscuring or hiding under other elements.

Well, this is a debugging trick for you.

Instructions: Paste the JavaScript snippet below in your browser's DevTools > Console.

z-index #

 1(() => {
 2
 3function debugElementsZ() {
 4  let elements = [...document.querySelectorAll("*")].reverse();
 5  elements
 6    .map((element) => {
 7      const { position, zIndex } =
 8        element.ownerDocument.defaultView.getComputedStyle(element, null);
 9      const z = parseInt(zIndex, 10) > -1;
10      if (zIndex === "auto") {
11        return undefined;
12      }
13      const { tagName, outerHTML, attributes } = element;
14      return {
15        element,
16        zIndex: z,
17        position,
18      };
19    })
20    .filter(Boolean);
21  elements = elements.sort((a, b) => b.zIndex - a.zIndex);
22  console.table(
23    elements.map((item) => ({
24      element: item.element,
25      textContent: (item.textContent || "").trim() + "…",
26      zIndex: item.zIndex,
27      position: item.position,
28    }))
29  );
30}
31
32debugElementsZ();
33
34})();