Last active
February 23, 2021 01:50
-
-
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
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
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)}}); |
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
// 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