Search code examples
javascriptjquerytagname

jQuery/javascript replace tag type


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 I lose other properties etc.


Solution

  • Completely untested, but giving this a whirl:

    $("td").each(function(index) {
      var thisTD = this;
      var newElement = $("<th></th>");
      $.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