Created
February 10, 2021 15:35
-
-
Save SeanMcP/ade3cb371d697709b3b95c5d539d888f to your computer and use it in GitHub Desktop.
Add anchors to all headings with an id
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
// ==UserScript== | |
// @name Anchored Headings | |
// @namespace https://seanmcp.com | |
// @version 0.1 | |
// @description Add anchors to all headings with an id | |
// @author Sean McPherson | |
// @match *://*/* | |
// @grant none | |
// ==/UserScript== | |
(function anchoredHeadings() { | |
"use strict"; | |
try { | |
const headings = document.querySelectorAll( | |
'[id]:is(h1,h2,h3,h4,h5,h6,[role="heading"])' | |
); | |
headings.forEach((node) => { | |
const href = `#${node.id}`; | |
// Check for existing anchor | |
if (node.querySelector(`a[href="${href}"]`)) return; | |
const anchor = document.createElement("a"); | |
anchor.href = href; | |
// HTML anchor (usually rendered as emoji) | |
anchor.innerHTML = "⚓"; | |
anchor.setAttribute("aria-label", "Link to this heading"); | |
anchor.style.display = "inline-block"; | |
anchor.style.paddingLeft = "0.5rem"; | |
anchor.title = "Anchored heading"; | |
node.appendChild(anchor); | |
}); | |
} catch {} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment