Reputation: 385
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
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>')
})
});
Upvotes: 7
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