Skip to content

Instantly share code, notes, and snippets.

@webarthur
Last active July 30, 2023 20:11
Show Gist options
  • Save webarthur/b5eb201a9743d1571cd0bb19ba91701f to your computer and use it in GitHub Desktop.
Save webarthur/b5eb201a9743d1571cd0bb19ba91701f to your computer and use it in GitHub Desktop.
Adds line numbers to code blocks on the web page - version 1
/**
* 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)
@linuxguist
Copy link

Thank You. Very Helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment