jQuery/javascript replace tag type

后端 未结 8 1521
抹茶落季
抹茶落季 2020-12-02 23:42

Is there an easy way to loop through all td tags and change them to th? (etc).

My current approach would be to wrap them with the th and then remove the td, but then

相关标签:
8条回答
  • 2020-12-03 00:27
    document.body.innerHTML=document.body.innerHTML.replace(/(\<td\>)|(\<td\s)|(\<\/td\>)/gi,function(x){return x.replace("td","th");})
    
    0 讨论(0)
  • 2020-12-03 00:28

    Slight addition to @GlenCrawford answer, to also preserve inner text with the line:

    newElement.text($(value).text());
    

    All together now:

    $("td").each(function(index) {
      var thisTD = this;
      var newElement = $("<th></th>");
      newElement.text($(value).text());
      $.each(this.attributes, function(index) {
        $(newElement).attr(thisTD.attributes[index].name, thisTD.attributes[index].value);
      });
      $(this).after(newElement).remove();
    });
    
    0 讨论(0)
提交回复
热议问题