Last active
December 3, 2025 22:45
-
-
Save dewomser/b609ac2b427854c14ea7c08ba09a0e3f to your computer and use it in GitHub Desktop.
Mit Javasript nachträgkich Anchor-Links in eine Webseite einbauen
This file contains hidden or 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
| <html> | |
| <div id="anchors"></div> | |
| … | |
| <p>Lorem Ipsun <strong>trallala</strong> und noch mehr Zeugs</p> | |
| <p><strong>trullulu</strong> Lora ipsa macht Unsinn</p> | |
| <p>In die Pfanne eine <strong>Bratwurstlegen</strong></p> | |
| <p>This girl named <strong> Lolo </strong> is a dancer</p> | |
| <p>Kein anckor für diese Teile</p | |
| <br />Anderes Zeugs mit <strong>Strong</strong>,aber ohne Anchor Link | |
| <p><strong>Test</strong> and I know her</p> | |
| <p>Ein Beispiel für <a href="https://www.untergang.de/index.php/dewomser-auf-mastodon/aus-meinem-zettelkasten-fuer-aphorismen/aus-meinem-zettelkasten-fuer-aphorimen-2023">dieses Skript</a></p> | |
| … | |
| <script> | |
| document.addEventListener("DOMContentLoaded", function() { | |
| const paragraphs = Array.from(document.querySelectorAll("p")); | |
| const anchors = []; | |
| paragraphs.forEach(function(paragraph) { | |
| const strong = paragraph.querySelector("strong"); | |
| if (strong && strong.textContent.trim().length > 0) { | |
| const id = strong.textContent.trim().replace(/\s+/g, "-"); | |
| strong.setAttribute("id", id); | |
| const anchor = document.createElement("a"); | |
| anchor.setAttribute("href", "#" + id); | |
| anchor.textContent = strong.textContent.trim(); | |
| anchors.push(anchor.outerHTML); | |
| } | |
| }); | |
| // Place the anchor list inside <div id="anchors"> at top of <body> | |
| let anchorsDiv = document.getElementById("anchors"); | |
| if (!anchorsDiv) { | |
| anchorsDiv = document.createElement("div"); | |
| anchorsDiv.id = "anchors"; | |
| document.body.insertBefore(anchorsDiv, document.body.firstChild); | |
| } | |
| if (anchors.length) { | |
| anchorsDiv.innerHTML = anchors.join(", "); | |
| } | |
| }); | |
| </script> | |
| </html> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Jetzt ausprobieren !
https://onecompiler.com/html/446hj3gxw