Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace < and > with &lt; and &gt; with jQuery or JS

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.

like image 486
sulfureous Avatar asked Dec 11 '22 12:12

sulfureous


2 Answers

Assuming you just want to escape all HTML:

$(".codeIt").text($(".codeIt").html());
like image 178
Prisoner Avatar answered Dec 27 '22 12:12

Prisoner


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;')
    );
});
like image 25
MDEV Avatar answered Dec 27 '22 13:12

MDEV