Omar Shamali

Change Element Type and Keep All Attributes in jQuery

Author: Omar Shamali
Writing Date:

Why would you need to change an element type?

  1. You might be working on HTML block builder and you need to give the admin control to change elements.
  2. Change of need, for example: you need a div to be turned into an unordered list (UL) when more than a paragraph in it.

What do you need to change an element type in jQuery?

  1. Medium knowledge of JavaScript if you wanna integrate the code with bigger code.
  2. Obviously, the jQuery plugin included in your page, no specific version needed, but this tutorial was tested on version 3.7.1.

How to change an element type?

The below code allows you to change any DOM element type to a new one, maintaining the original attributes and events.

//the original element
var meElem=$('#someDiv');

//the needed new type
var newType='h1';

//get original attributes
var attrs = {};
$.each($(meElem)[0].attributes,function(ind,attribute) {
	attrs[attribute.name]=attribute.value;
});

//make the new element
var newElem = $("<"+newType+"/>").append($(meElem).contents());
$(meElem).replaceWith(newElem);

//assign the original attributes to the new element
keys=Object.keys(attrs);
for(i=0;i<keys.length;i++){
	$(newElem).attr(keys[i],attrs[keys[i]]);
}