Skip to content

Instantly share code, notes, and snippets.

@gilbert
Created June 7, 2016 19:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gilbert/81f957044e6786922fe3153f94b3007e to your computer and use it in GitHub Desktop.
Save gilbert/81f957044e6786922fe3153f94b3007e to your computer and use it in GitHub Desktop.
JavaScript DOM: Render line numbers on pre with no dependencies
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="line-numbers.css">
</head>
<body>
<pre><code>function add (a, b) {
return a + b;
}</code></pre>
<script src="render.js"></script>
<script type="text/javascript">
renderLineNumbers( document.querySelector('pre') )
</script>
</body>
</html>
.line-numbers-wrapper {
position: relative;
padding-left: 0;
}
.line-numbers-wrapper > code { color: #bbb; }
.line-numbers-code {
margin: 0;
padding: 0;
overflow: visible;
position: absolute; top: 0px; left: 3.3rem; // You may have to adjust this
z-index: 1;
// App-specific anti-styles
border: none;
}
function renderLineNumbers (pre) {
var offsetTop = window.getComputedStyle(pre, null).getPropertyValue('padding-top');
pre.classList.add('line-numbers-code');
// Add class after clone
var wrapper = document.createElement('pre');
wrapper.classList.add('line-numbers-wrapper');
// Create line numbers
var lines = pre.innerHTML.split('\n');
if ( lines[lines.length-1] === '</code>' ) {
var closingTag = lines.pop();
lines[lines.length-1] += closingTag;
}
wrapper.innerHTML =
'<code>' +
lines
.map(function (_, i) {
return padLeft( (i+1) + '│', 4 )
})
.join('\n')
+ '</code>'
;
pre.style.top = offsetTop; // Offset clone by whatever padding you have set in app
pre.parentNode.replaceChild(wrapper, pre);
wrapper.appendChild(pre);
}
function padLeft (str,l) { return Array(l-str.length+1).join(" ") + str; }
@Stehlampe2020
Copy link

Stehlampe2020 commented Dec 21, 2022

in line-numbers.css:11 you have to change the comment from

left: 3.3rem; // You may have to adjust this

to

left: 3.3rem; /* You may have to adjust this */

because CSS doesn't support single-line comments ended by newline, it just supports block comments.

And please don't forget the opening html tag in example.html:2...

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