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">
<h2> This is an H2 </h2>
</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 <
and >
inside my <code>
tags.
I appreciate any help, Thanks.
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)
Thanks to everyone for their answers.
Assuming you just want to escape all HTML:
$(".codeIt").text($(".codeIt").html());
Plain JS for single code
element
var myCode = document.getElementById('mycode');
myCode.innerHTML = myCode.innerHTML.replace(/</g,'<').replace(/>/g,'>')
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,'<').replace(/>/g,'>')
}
}
or jQuery
$(".codeIt").each(function() {
$(this).html(
$(this).html().replace(/</g,'<').replace(/>/g,'>')
);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With