Created
July 30, 2023 20:11
-
-
Save webarthur/f5f54e89f4acc3a92a08b8e4815be2a3 to your computer and use it in GitHub Desktop.
Adds line numbers to code blocks on the web page - version 2
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 addLinesToCode () { | |
// Select all <pre><code> elements on the page | |
document.querySelectorAll('pre code') | |
.forEach(container => { | |
// Get code lines | |
const lines = (container.textContent.match(/\n/g)||[]).length + 1 | |
// Skip containers with only one line | |
if (lines <= 1) { | |
return | |
} | |
// Add class .line-numbers to parent node <pre> | |
container.parentNode.classList.add('line-numbers') | |
// Populate the line numbers | |
let numbers = '' | |
for (let i = 1; i <= lines; i++) { | |
numbers += `${ i }\n` | |
} | |
// Create a container for line numbers | |
const div = document.createElement('div') | |
div.setAttribute('aria-hidden', 'true') | |
div.classList.add('line-numbers-col') | |
div.textContent = numbers | |
// Insert the container before the code | |
container.insertAdjacentElement('beforebegin', div) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment