jQuery/javascript replace tag type

后端 未结 8 1556
抹茶落季
抹茶落季 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条回答
  •  旧时难觅i
    2020-12-03 00:26

    Completely untested, but giving this a whirl:

    $("td").each(function(index) {
      var thisTD = this;
      var newElement = $("");
      $.each(this.attributes, function(index) {
        $(newElement).attr(thisTD.attributes[index].name, thisTD.attributes[index].value);
      });
      $(this).after(newElement).remove();
    });
    

    I'm looking and looking at it, and I can't think of a reason why it wouldn't work!

    1) loop through each td element
    2) create a new th element
    3) for each of those td's, loop over each of its attributes
    4) add that attribute and value to the new th element
    5) once all attributes are in place, add the element to the DOM right after the td, and remove the td

    Edit: works fine: http://jsbin.com/uqofu3/edit

提交回复
热议问题