0

Given the following HTML, how would I go about encoding the HTML entities inside the <pre><code class="language-html"></code></pre> block? n.b., on the actual page where this will be used there are many such blocks.

<div><strong>Rendered</strong>
    <div>This is a div, which contains a <p>p</p> and a <span>span</span>.</div>
</div>

<div><strong>Code</strong>
    <pre><code class="language-html">
        <div>This is a div, which contains a <p>p</p> and a <span>span</span>.</div>
    </code></pre>
</div>

The goal is to have this output the following:

This is a div, which contains a p and a span.

<div>This is a div, which contains a <p>p</p> and a <span>span</span>.</div>

(i.e., the first copy of the code should render, while the second should merely display.)

Edit (14 Feb 2016): HTML-encoding lost when attribute read from input field addresses a slightly different issue and, consequently, this is not a duplicate.

Community
  • 1
  • 1
Zyniker
  • 283
  • 3
  • 14
  • Possible duplicate of [HTML-encoding in JavaScript/jQuery](http://stackoverflow.com/questions/1219860/html-encoding-in-javascript-jquery) – Rhumborl Feb 13 '16 at 12:09

1 Answers1

1

A simple solution is to grab the html(), then set it as the text():

$('pre > code.language-html').text(function() {
 $(this).text($(this).html());
})

// or simpler
//$('pre > code.language-html').text(function() { return $(this).html(); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<div>This is a div, which contains a <p>p</p> and a <span>span</span>.</div>

<div><pre><code class="language-html">
    <div>This is a div, which contains a <p>p</p> and a <span>span</span>.</div>
</code></pre></div>

<div><pre><code class="language-html">
    <div>This is a div, which contains a <p>p</p> and a <span>span</span>.</div>
</code></pre></div>
Rhumborl
  • 16,349
  • 4
  • 39
  • 45