The other day I wrote a post titled “How to highlight code on a webpage when you’re using Markdown to create that webpage” that discussed using highlight.js to make code displayed on a webpage show up in various colors. In that post I talked about a key feature of highlight.js: it automatically detects the language of the code & colorizes accordingly.

In a footnote on that post I mentioned that if you want, or if highlight.js is confused & can’t figure out which language is used, you can add a class that specifies the language to either <pre> or <code>. Like this:

<pre class="html"><code>This is <em>code</em>.
</code></pre>

Here’s the rub: as I explained in the post, I like to use Markdown to write my webpages1, & Markdown doesn’t allow you to attach classes to elements, since you’re not working directly with the HTML. So how do you attach a class to code that you’re not writing? In other words, I paste this into my webpage (indented, which is what you do to indicate to Markdown that it’s a code block):

strong {
  font-weight: bold;
}

PHP Markdown Extra automatically renders that into this HTML:

<pre><code>strong {
  font-weight: bold;
}
</code></pre>

But what I really want is this:

<pre><code class="css">strong {
  font-weight: bold;
}
</code></pre>

So how do I put that class="css" in there automatically, since I can’t do it by hand?

Turns out, support for doing just that is built into jQuery, & it also turns out, in a fine moment of serendipity, that the CMS I use, Concrete5, calls jQuery on every page. So all I had to do was add this to the page, in the <head>:

<script type="text/javascript">
$(function() {
  $("code").addClass("css");
});
</script>

After the page finished loading, class="css" was placed into each <code>, resulting in <code class="css">.

For more information about this jQuery method, check out http://api.jquery.com/addClass/.

Of course, there’s also a counter to the addClass method: the removeClass method, which you can read about at http://api.jquery.com/removeClass/. Sample code:

<script type="text/javascript">
$(function() {
  $("code").removeClass("wackadoo");
});
</script>

What’s really nice is that you can combine the two, like this:

<script type="text/javascript">
$(function() {
  $("code").removeClass("wackadoo").addClass("css");
});
</script>

Understand that all of the JavaScript shown here doesn’t really alter the actual HTML itself, so going to View Source won’t show any changes. Why? Because the HTML isn’t changed when you use JavaScript to change the DOM. In order to verify that things have been added or removed, you’ll need to use a special browser tool that lets you see the DOM as the browser sees it:

I can’t wait to use these methods in my CSS course at Washington University in St. Louis! When I do, I’ll post about it here.

  1. Specifically, PHP Markdown Extra