Last active
July 30, 2023 20:11
-
-
Save webarthur/b5eb201a9743d1571cd0bb19ba91701f to your computer and use it in GitHub Desktop.
Adds line numbers to code blocks on the web page - version 1
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
/** | |
* Adds line numbers to code blocks on the page. | |
*/ | |
function addLineNumbersToCode () { | |
// Select all <pre><code> elements on the page | |
document.querySelectorAll('pre code') | |
.forEach(container => { | |
// Get code lines | |
const lines = container.innerHTML.split('\n') | |
// Skip containers with only one line | |
if (lines.length <= 1) { | |
return | |
} | |
// Add line numbers to each line of code | |
let newCode = lines | |
.map((line, i) => `<span class='line-number'>${ i + 1 }</span>${ line }`) | |
.join('\n') | |
// Update the container with the new code | |
container.innerHTML = newCode; | |
}) | |
} | |
// Call the addLinesToCode function when the window finishes loading | |
window.addEventListener('load', addLinesToCode) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank You. Very Helpful.