// ==UserScript== | |
// @name Apply Anchor Tags to Headers with Ids | |
// @description Finds all header tags that have ids and puts an anchor inside it | |
// @match *://*/* | |
// @exclude https://imois.in/games/travle/* | |
// ==/UserScript== | |
function applyAnchorTagsToHeadersWithIds() { | |
// get all header elements on the page | |
const headers = document.querySelectorAll("h1, h2, h3, h4, h5, h6") | |
// only work with those that have ids | |
const headersWithIds = [...headers].filter( x => x.id ) | |
const headerChildrenHaveIds = [...headers].filter(x => [...x.children].filter(c => c.id)) | |
// If there aren't any headers with ids, bye | |
if (headersWithIds.length === 0) return | |
// loop through each header | |
headersWithIds.forEach(applyAnchorIfHeaderHasNoAnchor) | |
// loop through header children | |
headerChildrenHaveIds.forEach(x => { | |
[...x.children].filter(c => c.id).forEach(setInnerHTMLToAnchor) | |
}) | |
} | |
const applyAnchorIfHeaderHasNoAnchor = header => { | |
// check if the header already has anchors as children | |
const headerHasAnchors = [...header.children].some(x => x.tagName === "A") | |
if (!headerHasAnchors) { | |
setInnerHTMLToAnchor(header) | |
} | |
} | |
const setInnerHTMLToAnchor = (tag) => { | |
// set the tag's innerHTML to an anchor that points to its id and | |
// the textContent of the anchor is the textContent of the tag | |
tag.innerHTML = `<a href="#${tag.id}"># ${tag.textContent}</a>` | |
} | |
// do the thing | |
applyAnchorTagsToHeadersWithIds() |