Replace the HTML tag with a new tag

How to replace html tag with 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 must also be replaced.

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

Must be changed to:

 <div class='replace_this'> <div> <div> All table, tr, and td tag are replaced with div tag </div> </div> </div> 
+4
source share
2 answers

You need to start 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

+7
source

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/

0
source

Source: https://habr.com/ru/post/1385365/


All Articles