HTML Decoder

Parsing a specified block of HTML into a string. A complement to the .codeblock() jQuery function.

Viva la automation!

As part of my code sample library, I wanted to find a way to dynamically insert a block of HTML, just like my CSS and JavaScript decoders.

Calling innerHTML doesn’t work, as I will also want the container element, not just the children. We also need to convert the string to HTML entities, otherwise the code block will simply render as HTML.

So here’s what we do.

First, we create a container element and clone the HTML we want into it. We then get the innerHTML of that element, which is the full string. (For the sake of being tidy, we then kill the container element.)

Next, we use a regex to convert the necessary brackets and quotes into HTML entities. Rather than tacking on regex after regex, I’m using a switch statement inside the replace() function to discern one entity over the other.

Last, we append our sanitized string into the code container and run codeblock(). Done.

Figure 1

Blueberries
Pancakes with blueberries.

Le Code

Le Output