Skip to content

Instantly share code, notes, and snippets.

@Pinjasaur
Last active February 23, 2021 01:50
Show Gist options
  • Save Pinjasaur/12660009a0c92efab64466110c4bbf03 to your computer and use it in GitHub Desktop.
Save Pinjasaur/12660009a0c92efab64466110c4bbf03 to your computer and use it in GitHub Desktop.
Prepend an anchor tag inside elements with IDs to easily get permalinks to document fragments e.g., https://domain.tld/#my-id
javascript:Array.from(document.querySelectorAll("[id]")).forEach(e=>{if(/[A-Za-z][-A-Za-z0-9_:.]*/.test(e.id)&&!e.querySelector(`a[href="#${e.id}"]`)){const r=document.createElement("a");r.innerHTML="#",r.href=`#${e.id}`,e.insertBefore(r,e.firstChild)}});
// Optionally change the initial selector e.g., only headers: "h1, h2, h3, h4, h5, h6"
Array.from(document.querySelectorAll("[id]")).forEach($el => {
// ID looks legit and there isn't already a link to it (within the found element)
if (/[A-Za-z][-A-Za-z0-9_:.]*/.test($el.id) && !$el.querySelector(`a[href="#${$el.id}"]`)) {
const $link = document.createElement("a")
$link.innerHTML = "#"
$link.href = `#${$el.id}`
$el.insertBefore($link, $el.firstChild)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment