unknown
unknown

Reputation: 385

Replace HTML tag with a new tag

How can I replace the html tag with a new tag using jQuery?

I have many table tags and I want to replace a specific table containing a class. All of its' child nodes should be replaced too.

<table class='replace_this'>
    <tr>
        <td>
            All table, tr, and td tag are replaced with div tag
        </td>
    </tr>
</table>

Should be changed to:

<div class='replace_this'>
    <div>
        <div>
            All table, tr, and td tag are replaced with div tag
        </div>
    </div>
</div>

Upvotes: 4

Views: 598

Answers (2)

Joe
Joe

Reputation: 82564

You have to start from the inside out:

$('.replace_this td').each(function() {
    $(this).replaceWith(function() {
        return $('<div>' + this.innerHTML + '</div>')
    })
});

$('.replace_this tr').each(function() {
    $(this).replaceWith(function() {
        return $('<div>' + this.innerHTML + '</div>')
    })
});

$('table.replace_this ').each(function() {
    $(this).replaceWith(function() {
        return $('<div class="replace_this">' + this.innerHTML + '</div>')
    })
});

Example

Upvotes: 7

Samich
Samich

Reputation: 30095

I have something like this:

$.each(['td', 'tr', 'table'], function(index, value){
    $(value).replaceWith(function() {
      return '<div>' + $(this).html() + '</div>';
    });
});

Code: http://jsfiddle.net/nHpCc/4/

Upvotes: 0

Related Questions