3

I have the following code:

<div class="normal">
    <div>
        <div>~Content 1~</div>
    </div>
</div>

<div class="normal replace">
    <a href="#">
        <div>~Content 2~</div>
    </a>
</div>

Using jQuery, I want to replace the <a> tag inside <div class="normal replace"> with normal <div> tag while keeping it's content.

<div class="normal replace">
    <div="result">
        <div>~Content 2~</div>
    </div>
</div>

6 Answers6

15
$('.normal > a').replaceWith(function() {
    return $('<div/>', {
        html: this.innerHTML
    });
});

http://jsfiddle.net/VMxAL/

Ram
  • 143,282
  • 16
  • 168
  • 197
5

Try something like this:

// Select the 'a' tag to be replaced and call the replaceWith method
$('.normal a').replaceWith(function(){
    // Execute a callback to generate contents of the replacement
    // The $('<div>') part creates a div
    return $('<div>', {
        html: this.innerHTML // This takes the html of the 'a' tag and copies it to the new div
    });
});

The jQuery replaceWith method takes the the item and replaces it with what is returned by the callback function.

See here for more information

Ben Carey
  • 16,540
  • 19
  • 87
  • 169
2

here you go orignally take from here Using jQuery to replace one tag with another

$('div.normal a').contents().unwrap().wrap('<div id='result'/>');
Community
  • 1
  • 1
The Mechanic
  • 2,301
  • 1
  • 26
  • 37
2

Try this -

$('div.normal.replace a').find('div').unwrap().wrap("<div id='result'/>");
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
0

Use the following $('div.normal.replace a').replaceWith( "" + $('div.normal.replace a').html() + "" );

Swati Sachdeva
  • 253
  • 2
  • 11
0

Please click on the jsfiddle example i tried for you below.

Click here for JS Fiddle example

Hope that helps.

sanman
  • 57
  • 3