Skip to content

Instantly share code, notes, and snippets.

@SeanMcP
Created February 10, 2021 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SeanMcP/ade3cb371d697709b3b95c5d539d888f to your computer and use it in GitHub Desktop.
Save SeanMcP/ade3cb371d697709b3b95c5d539d888f to your computer and use it in GitHub Desktop.
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