DEV Community

Allan Simonsen
Allan Simonsen

Posted on

Sourcecode syntax highlighting in html with highlight.js

highlight.js example

In this article I will show you how to use the highlight.js JavaScript module to present your code beautifully syntax highlighted.

The code below is a simple html page with two source code samples in typescript and Python. The first example only has the plain source code. The second example shows the usage of the highlightjs-line-number addon that adds line numbers to the source code which makes it much easier to refer the lines in the code you want to show in your html page.

    <link rel="stylesheet" href="" />
    <script src=""></script>
    <script src=""></script>
    <h1>Source code highlighting</h1>
    <pre name="source" id="source1" ><code id="source" class="language-typescript">
class MyClass {
    public static myValue: string;
    constructor(init: string) {
        this.myValue = init;
import fs = require("fs");
module MyModule {
    export interface MyInterface extends Other {
        myProperty: any;
declare magicNumber number;
myArray.forEach(() => { }); // fat arrow syntax
    <pre name="source" id="source2" ><code id="source" class="language-python">
def somefunc(param1='', param2=0):
    r'''A docstring'''
    if param1 > param2: # interesting
        print 'Gre\'ater'
    return (param2 - param1 + 1 + 0b10l) or None

class SomeClass:

    <script lang="javascript">
        var source1 = document.getElementById('source1')

        var source2 = document.getElementById('source2')
        hljs.lineNumbersBlock(source2, {
            startFrom: 1
Enter fullscreen mode Exit fullscreen mode

Below you can see the result in the browser
Image description

You can read all the details about highlight.js and the highlightjs-line-number module here:

Top comments (0)