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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s