Skip to content

Instantly share code, notes, and snippets.

@andrefcdias
Last active October 24, 2023 14:35
Show Gist options
  • Save andrefcdias/09a76414fcf87c3c23b9da3afa56ca5a to your computer and use it in GitHub Desktop.
Save andrefcdias/09a76414fcf87c3c23b9da3afa56ca5a to your computer and use it in GitHub Desktop.
Heading level logger
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);
})();
@andrefcdias
Copy link
Author

Not my original code, but adapted to support elements with shadowRoot, so please let me know if you know the author for credit 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment