I noticed that the first answer wasn't quite what I needed, so I made a couple of modifications and figured I'd post it back here.
Improved replaceTag(<tagName>)
replaceTag(<tagName>, [withDataAndEvents], [withDataAndEvents])
Arguments:
- tagName: String
- The tag name e.g. "div", "span", etc.
- withDataAndEvents: Boolean
- "A Boolean indicating whether event handlers should be copied along with the elements. As of jQuery 1.4, element data will be copied as well." info
- deepWithDataAndEvents: Boolean,
- A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false)." info
Returns:
A newly created jQuery element
Okay, I know there are a few answers here now, but I took it upon myself to write this again.
Here we can replace the tag in the same way we use cloning.
We are following the same syntax as .clone() with the withDataAndEvents
and deepWithDataAndEvents
which copy the child nodes' data and events if used.
Example:
$tableRow.find("td").each(function() {
$(this).clone().replaceTag("li").appendTo("ul#table-row-as-list");
});
Source:
$.extend({
replaceTag: function (element, tagName, withDataAndEvents, deepWithDataAndEvents) {
var newTag = $("<" + tagName + ">")[0];
// From [Stackoverflow: Copy all Attributes](http://stackoverflow.com/a/6753486/2096729)
$.each(element.attributes, function() {
newTag.setAttribute(this.name, this.value);
});
$(element).children().clone(withDataAndEvents, deepWithDataAndEvents).appendTo(newTag);
return newTag;
}
})
$.fn.extend({
replaceTag: function (tagName, withDataAndEvents, deepWithDataAndEvents) {
// Use map to reconstruct the selector with newly created elements
return this.map(function() {
return jQuery.replaceTag(this, tagName, withDataAndEvents, deepWithDataAndEvents);
})
}
})
Note that this does not replace the selected element, it returns the newly created one.