Adding & removing CSS classes to HTML via jQuery
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:
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):
PHP Markdown Extra automatically renders that into this HTML:
But what I really want is this:
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>
:
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:
What’s really nice is that you can combine the two, like this:
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:
- Firefox: Firebug
- Safari: Right-click & Inspect Element to open the Web Inspector
- Chrome: Right-click & Inspect Element to open the Developer Tools
- IE: F12 Developer Tools
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.
-
Specifically, PHP Markdown Extra. ↩