How do I remove `<code></code>` from `<pre></pre>` with javascript?

409 Views Asked by At

The triple backticks in markdown render as <pre><code class="...">...</code></pre>. More specifically,

# in markdown
```java

```

# render as 
<pre>
<code class="java">
...
</code>
</pre>

# my expecting result (for Google code prettify):
<pre class="prettyprint linenums lang-java">
...
</pre>

My current solution is to add the following code but it doesn't work.

<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js?skin=son-of-obsidian></script>

 <script type="text/javascript">
 jQuery(document).ready(function () {
     $('pre code').each(function() {
         var code = $(this).html();
         var lang = $(this).attr('class');
         if (lang) {
             $(this).parent().attr('class', 'prettyprint linenums lang-'+lang).html(code);
         }
     });
     prettyPrint();
 });
 </script>

How do I remove <code class="...">...</code>?


I used SyntaxHighlighter <pre class="brush: java">...</pre> to highlighter my code blocks in WordPress + Windows Live Writer + PreCode(based on SyntaxHighlighter).

Currently, I turn to markdown. To insert a code blocks in markdown, I use

```java
code here
```

# OR

<pre class="brush: java">
code here
</pre>

Both of them doesn't work for me, because SyntaxHighlighter requires all left angle brackets inside <pre></pre> should be HTML entries escaped.

Therefore, I install Google code prettify but encounter the above issue (incompatiable).

2

There are 2 best solutions below

6
On BEST ANSWER

Try the below out and let me know if this works for you.

$('pre').each(function() {
     var el = $(this).find('code');
     var code = el.html();
     var lang = el.attr('class');
     if (lang) {
         $(this).addClass('prettyprint linenums lang-' + lang).html(code);
     }
 });

JSFiddle Demo

1
On

You are forgetting to remove the original code object from the pre element, causing the code to be duplicated. You should call $(this).remove(); to remove the old code object.