/home/posts/automatic-code-labels

Automatic Code Block Labels using Javascript

Published on

In another post, we explored adding custom labels to code blocks to give them some context, like a filename or language.

In Markdown, the language of a code block can be specified like so:

markdown

```python
import time

print(2 + 2)
```

Among other things, this allows Markdown processors to apply syntax highlighting to the code blocks. Since we’re already specifying the language, wouldn’t it be helpful to add an automatic code label with the language of the code we’re looking at?

#JavaScript Saves the Day

Here’s a snippet of JS I have written to work with Hugo, the static site generator I use to create this website.

javascript

var highlightBlocks = document.querySelectorAll(".highlight");

for( i=0; i < highlightBlocks.length; i++) {
	var highlightBlock = highlightBlocks[i];

	// get language data
	var codes = highlightBlock.querySelectorAll("[data-lang]");
	var lang = codes[0].getAttribute("data-lang");

	// check if custom label is already made
	if (highlightBlock.previousElementSibling.classList.contains("codeblock-label")) continue

	// create label element
	var label = document.createElement("p");
	label.classList.add("codeblock-label");
	label.innerHTML = lang;

	// insert label
	highlightBlock.parentNode.insertBefore(label, highlightBlock);
}

This JavaScript snippet finds all instances of syntax highlighting, figures out what language the code block is written in, ensures a custom label hasn’t been written, and then adds the label containing the language.

CSS can then be applied to the label with the .codeblock-label selector.

You can see it in action on the above code block!

Meet the Author

John Allbritten

Nashville, TN

I love learning new technologies, and I have a passion for open source. As I learn things, my notes turn into articles to share.

+

byte-sized tech articles.

delivered straight to your inbox.

Every month, receive a curated selection of tech articles.

What's this?

Related Posts