如何用th标签替换所有tr标签

mav*_*era 2 regex jquery html-table

我有一张这样的桌子:

<thead>    
    <tr class="row-2"><tr>
    <tr class="row-3">..<tr>
    <tr class="row-4">..<tr>
    <tr class="row-5">..<tr>
    <tr class="row-6">..<tr>
    <tr class="row-7"><tr>
    <tr class="row-8">..<tr>
    <tr class="row-9">..<tr>
    <tr class="row-10">..<tr>
    <tr class="row-11">..<tr>
</thead>
Run Code Online (Sandbox Code Playgroud)

如何使用jQuery将所有tr标签替换为thead标签内的th标签?

Tim*_*hle 6

获取表格html然后用th 替换所有出现或tr(参见RegExp获取更多信息).您可以将<thead>设置为具有ID并访问该ID.

$('#tableId').html($('#tableId').html().replace(/tr/gi, 'th'));
Run Code Online (Sandbox Code Playgroud)

这会将整个表中的所有tr改为th.

编辑 感谢jAndy提供更好的性能.

$('#mytable').find('tr').each(function() {
    var $this = $(this);
    $this.replaceWith('<th class="' + this.className + '">' + $this.text() + '</th>');
});
Run Code Online (Sandbox Code Playgroud)

.find()比$('#mytable> tr')快吗?