Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
80
rated 0 times [  83] [ 3]  / answers: 1 / hits: 26978  / 11 Years ago, wed, july 31, 2013, 12:00:00

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.


More From » jquery

 Answers
16

Assuming you just want to escape all HTML:



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

[#76630] Tuesday, July 30, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shylaelisan

Total Points: 37
Total Questions: 94
Total Answers: 110

Location: Angola
Member since Tue, May 5, 2020
4 Years ago
;