I need to convert a DOM element to a different type (as in HTML tag name, a to p in this case), but still retain all the original elements attribut
A more modern (2020+) approach is:
function changeTag (element, tag) {
// prepare the elements
const newElem = document.createElement(tag)
const clone = element.cloneNode(true)
// move the children from the clone to the new element
while (clone.firstChild) {
newElem.appendChild(clone.firstChild)
}
// copy the attributes
for (const attr of clone.attributes) {
newElem.setAttribute(attr.name, attr.value)
}
return newElem
}
Compared to @James answer, you don't need to copy the cssText because it's already taken care by the browser. You also don't need the string/number dom properties since those are also properly migrated. It's also best to work on the cloned node only, not both of them (clone and elem)