I like the idea of @AndrewWhitaker and others, to use a jQuery plugin -- to add the changeElementType() method. But a plugin is like a blackbox, no mater about the code, if it is litle and works fine... So, performance is required, and is most important than code.
"Pure javascript" have better performance than jQuery: I think that @FelixKling's code have better performance than @AndrewWhitaker's and others.
Here is a method I use to replace html tags in jquery:
// Iterate over each element and replace the tag while maintaining attributes
$('b.xyzxterms').each(function() {
// Create a new element and assign it attributes from the current element
var NewElement = $("<h1 />");
$.each(this.attributes, function(i, attrib){
$(NewElement).attr(attrib.name, attrib.value);
});
// Replace the current element with the new one and carry over the contents
$(this).replaceWith(function () {
return $(NewElement).append($(this).contents());
});
});
@Jazzbo's answer returned a jQuery object containing an array of jQuery objects, which wasn't chainable. I've changed it so that it returns an object more similar to what $.each would have returned:
Here is my version. It's basically @fiskhandlarn's version, but instead of constructing a new jQuery object, it simply overwrites the old elements with the newly created ones, so no merging is necessary.
Demo: http://jsfiddle.net/0qa7wL1b/
$.fn.changeElementType = function( newType ){
var $this = this;
this.each( function( index ){
var atts = {};
$.each( this.attributes, function(){
atts[ this.name ] = this.value;
});
var $old = $(this);
var $new = $('<'+ newType +'/>', atts ).append( $old.contents() );
$old.replaceWith( $new );
$this[ index ] = $new[0];
});
return this;
};