Dynamically change HTML tag of elements

/**
 * Author: Shiva Bhusal
 * website: cbabhusal.wordpress.com
 * This function replaces the DOM elements's tag name with you desire
 * Example:
 * replaceElem('header','ram');
 * replaceElem('div.header-one','ram');
 */
function replaceElem(targetId, replaceWith){
 $(targetId).each(function(){
 var attributes = concatHashToString(this.attributes);
 var replacingStartTag = '<' + replaceWith + attributes +'>';
 var replacingEndTag = '</' + replaceWith + '>';
 $(this).replaceWith(replacingStartTag + $(this).html() + replacingEndTag);
 });
}
replaceElem('div','span');
/**
 * This function concats the attributes of old elements
 */
function concatHashToString(hash){
 var emptyStr = '';
 $.each(hash, function(index){
 emptyStr += ' ' + hash[index].name + '="' + hash[index].value + '"';
 });
 return emptyStr;
}
Codepen link : 

Leave a comment