views:

222

answers:

2

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.

+1  A: 

This might work, but I haven't tested it extensively:

var tds = document.getElementsByTagName("td");
while(tds[0]){
    var t = document.createElement("th");
    var a = tds[0].attributes;
    for(var i=0;i<a.length;i++) t.setAttribute(a[i].nodeName,a[i].nodeValue);
    t.innerHTML = tds[0].innerHTML;
    tds[0].parentNode.insertBefore(t,tds[0]);
    tds[0].parentNode.removeChild(tds[0]);
}

I hope it helps in some way.

tau
+5  A: 

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

GlenCrawford