Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to replace one tag with another

Goal:

Using jQuery, I'm trying to replace all the occurrences of:

<code> ... </code>

with:

<pre> ... </pre>

My solution:

I got as far as the following,

$('code').replaceWith( "<pre>" + $('code').html() + "</pre>" );

The problem with my solution:

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.

like image 680
jon Avatar asked Aug 17 '11 13:08

jon


People also ask

How to replace one tag to another in jQuery?

$('code'). replaceWith( "<pre>" + $('code'). html() + "</pre>" );


2 Answers

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());
});
like image 123
Felix Kling Avatar answered Oct 30 '22 04:10

Felix Kling


This is much nicer:

$('code').contents().unwrap().wrap('<pre/>');

Though admittedly Felix Kling's solution is approximately twice as fast:

like image 24
Jens Roland Avatar answered Oct 30 '22 05:10

Jens Roland