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.
To replace a DOM element with the specified HTML or DOM elements using jQuery, use the replaceWith() method. The replaceWith (content) method replaces all matched elements with the specified HTML or DOM elements. This returns the JQuery element that was just replaced, which has been removed from the DOM.
Choose the Tag you want to rename. Right-click on it and choose Rename to rename the Tag. You can also click on the name of the Tag to rename quickly. Change the name from the colors to anything you like and hit Enter.
The following is a jQuery plugin to replace the tag name of DOM elements.
(function($) { $.fn.replaceTagName = function(replaceWith) { var tags = [], i = this.length; while (i--) { var newElement = document.createElement(replaceWith), thisi = this[i], thisia = thisi.attributes; for (var a = thisia.length - 1; a >= 0; a--) { var attrib = thisia[a]; newElement.setAttribute(attrib.name, attrib.value); }; newElement.innerHTML = thisi.innerHTML; $(thisi).after(newElement).remove(); tags[i] = newElement; } return $(tags); }; })(window.jQuery);
(function(e){e.fn.replaceTagName=function(t){var n=[],r=this.length;while(r--){var i=document.createElement(t),s=this[r],o=s.attributes;for(var u=o.length-1;u>=0;u--){var a=o[u];i.setAttribute(a.name,a.value)}i.innerHTML=s.innerHTML;e(s).after(i).remove();n[r]=i}return e(n)}})(window.jQuery);
Include the above minified source in your javascript after jQuery.
Then you can use the plugin like this:
$('div').replaceTagName('span'); // replace all divs with spans
Or in your case this:
$('td').replaceTagName('th');
jQuery selectors work as expected
$('.replace_us').replaceTagName('span'); // replace all elements with "replace_us" class with spans $('#replace_me').replaceTagName('div'); // replace the element with the id "replace_me"
jsFiddle with Qunit tests
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With