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.

1

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

It may be simple, but it works for what I'm doing. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.