Last active
January 26, 2022 20:30
-
-
Save Heydon/d2a3291c89ebdd6a5b1b20b0a83a3190 to your computer and use it in GitHub Desktop.
This file contains 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
// set heading level based on the closest heading before the node | |
const setLevel = (node, nodeSelector) => { | |
// Get all relevant nodes and reverse the array (destructive) | |
let allNodes = [...document.querySelectorAll(`h1, h2, h3, h4, h5, h6, ${nodeSelector}`)].reverse(); | |
// Truncate the array to make the target node the first item | |
let index = allNodes.indexOf(allNodes.find(n => n.contains(node))); | |
let truncated = allNodes.slice(index); | |
// Find the next node thats a heading | |
let heading = truncated.find(n => n.matches('h1, h2, h3, h4, h5, h6')); | |
// Return the next highest level based on the matched heading's level | |
return Math.min(parseInt(heading.tagName.substring(1)) + 1, 6); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment