Using jQuery, I'm trying to replace all the occurrences of:
<code> ... </code>
with:
<pre> ... </pre>
I got as far as the following,
$('code').replaceWith( "<pre>" + $('code').html() + "</pre>" );
but the issues is that it's replacing everything between the (second, third, fourth, etc)"code" tags with the content between the first "code" tags.
e.g.
<code> A </code>
<code> B </code>
<code> C </code>
becomes
<pre> A </pre>
<pre> A </pre>
<pre> A </pre>
I think I need to use "this" and some sort of function but I'm afraid I'm still learning and don't really understand how to piece a solution together.
$('code'). replaceWith( "<pre>" + $('code'). html() + "</pre>" );
You can pass a function to .replaceWith
[docs]:
$('code').replaceWith(function(){
return $("<pre />", {html: $(this).html()});
});
Inside the function, this
refers to the currently processed code
element.
DEMO
Update: There is no big performance difference, but in case the code
elements have other HTML children, appending the children instead of serializing them feels to be more correct:
$('code').replaceWith(function(){
return $("<pre />").append($(this).contents());
});
This is much nicer:
$('code').contents().unwrap().wrap('<pre/>');
Though admittedly Felix Kling's solution is approximately twice as fast:
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