Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add anchors to all headings with an id
// ==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