Last active
October 24, 2023 14:35
-
-
Save andrefcdias/09a76414fcf87c3c23b9da3afa56ca5a to your computer and use it in GitHub Desktop.
Heading level logger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
javascript: void (function () { | |
let result = ""; | |
for (const node of document.querySelectorAll("h1, h2, h3, h4, h5, h6")) { | |
const label = getNodeValue(node); | |
if ( | |
!node.closest('[aria-hidden=""], [aria-hidden="true"]') && | |
(node.offsetHeight > 0 || node.offsetWidth) && | |
label | |
) { | |
const headingLevel = parseInt(node.tagName.match(/\d/)[0]); | |
result += `${new Array(2 * (headingLevel - 1)) | |
.fill("-") | |
.join("")}${node.tagName.toLowerCase()}: ${label}\n`; | |
} | |
function getNodeValue(node) { | |
const labbelledBy = node.getAttribute("aria-labelledby"); | |
return ( | |
node.getAttribute("alt") || | |
node.getAttribute("aria-label") || | |
(labbelledBy && | |
getInnerContent(document.getElementById(labbelledBy))) || | |
getInnerContent(node) | |
).trim(); | |
} | |
function getInnerContent(node) { | |
if (node.shadowRoot) { | |
return getInnerContent(node.shadowRoot); | |
} | |
let result = ""; | |
for (const childNode of node.childNodes) { | |
const nodeValue = ( | |
childNode instanceof HTMLElement | |
? getNodeValue(childNode) | |
: childNode.textContent || "" | |
).trim(); | |
result += `${nodeValue} `; | |
} | |
return result; | |
} | |
} | |
console.log(result); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not my original code, but adapted to support elements with
shadowRoot
, so please let me know if you know the author for credit 🙌