4

I've been searching for a day or so how to do something with JS or jQuery and found a couple of solutions but nothing solid yet.

I want to use this:

<code class="codeIt">

  <h2> This is an H2 </h2>

</code>

And I want the output to be:

<h2> This is an H2 </h2>

I know I can achieve this by doing:

<code class="codeIt">

  &lt;h2&gt; This is an H2 &lt;/h2&gt;

</code>

...But I would like to not do a manual search and replace on my code in those blocks and rather have it done on the fly in the browser. Is this possible?

I'm pretty noob with jQuery so I've tried .replaceWith or JavaScript's .replace but so far I've not gotten where I need to be with it. I'm either replacing the whole tag or doing something else wrong.

My question is: How would I write a simple jQuery (or regular JS) to help me replace my < and my > with HTML entities like &lt; and &gt; inside my <code> tags.

I appreciate any help, Thanks.

UPDATE:

I managed to get it working nice how @Prisoner explained, it's very nifty, however this in my particular case needed a little extending because I have more than one block of code with the .codeIt class, so I had to make it check each element and output... otherwise it would keep making the same output (like the first block)

Here is the fiddle

Thanks to everyone for their answers.

5

6 Answers 6

6

Assuming you just want to escape all HTML:

$(".codeIt").text($(".codeIt").html());
4
  • If you run that code on this page (changing selector to just "code" of course), it fails quite spectacularly
    – MDEV
    Jul 31, 2013 at 9:17
  • This seems like the solution I'm looking for definitively, however, it's just not working for me, it keeps rendering the <h2> as a heading an not as text. What could I be possibly doing wrong by implementing one line of code? hehe... I know I have the selector right. I tried it with a <code> tag or a <div> tag and no go.
    – sulfureous
    Jul 31, 2013 at 9:24
  • @sulfureous, it must be your inclusion of jQuery or the way you're running the code. This basic example works fine: jsfiddle.net/T8kBt
    – Prisoner
    Jul 31, 2013 at 9:31
  • Thanks, this seems to work now. Must have been a cache issue.
    – sulfureous
    Jul 31, 2013 at 9:35
5

Plain JS for single code element

var myCode = document.getElementById('mycode');
myCode.innerHTML = myCode.innerHTML.replace(/</g,'&lt;').replace(/>/g,'&gt;')

Plain JS for multiple code elements

var codeEls = document.getElementsByTagName('code');
for(var i in codeEls)
{
    if(parseInt(i)==i)
    {
        var codeEl = codeEls[i];
        if(codeEl.className.match(/\bcodeIt\b/)!==null) codeEl.innerHTML = codeEl.innerHTML.replace(/</g,'&lt;').replace(/>/g,'&gt;')
    }
}

or jQuery

$(".codeIt").each(function() {
    $(this).html(
        $(this).html().replace(/</g,'&lt;').replace(/>/g,'&gt;')
    );
});
0
1

You could use the text function of jquery:

var myText = $('.codeIt').html();

var escapedText = $('.codeIt').text(myText).html();
1
  • Thank you @harpax this definitively works too, but it's longer than the accepted answer and it does the same... But it works, no doubt.
    – sulfureous
    Jul 31, 2013 at 9:39
1
var t = $('.codeIt').html();

$('.codeIt').text(t).html();

Look at this fiddle http://jsfiddle.net/kU8bV/1/

2
  • The fiddle doesn't link to your fiddle, it just links to jsfiddle.net
    – sulfureous
    Jul 31, 2013 at 9:21
  • This worked for me as in the fiddle. It's simple and it makes sense now, so we are creating a variable called t and it equals to the HTML of the .codeIt element and then we are taking that same .codeIt element and using the .text() method to print the t variable as text and add it to the HTML. Am I understanding this right?
    – sulfureous
    Jul 31, 2013 at 9:32
0
$('code').html($('code').html().replace(/</g, '&lt;').replace(/>/g, '&gt;'));
2
  • 2
    This will only replace the first instance of < and >. You need to do a global regexp replace, like @SmokeyPHP. Jul 31, 2013 at 9:11
  • Please include a description of your solution for it to be a more helpful answer.
    – Tony
    Jul 31, 2013 at 9:33
0

Assuming you want to code all the html in codeIt class :

<script type="text/javascript">
        function htmlEncode(value){
            if (value) {
                return jQuery('<div />').text(value).html();
            } else {
                return '';
            }
        }

        function htmlDecode(value) {
            if (value) {
                return $('<div />').html(value).text();
            } else {
                return '';
            }
        }       
        $('.codeIt').each(function() {
            myEncodedString = htmlEncode($(this).html());
            $(this).html(myEncodedString);
        });
</script>

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.