Last active
November 12, 2021 02:42
-
-
Save Daniel-Hug/d245b53b6195b9596c00659cb17cda6c to your computer and use it in GitHub Desktop.
JS function: replace tag name but keep element contents. Source: http://stackoverflow.com/a/15086834/552067
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Replace tag name but keep element contents | |
function changeTag(el, newTagName, keepAttributes) { | |
var newEl = document.createElement(newTagName); | |
// Copy the children | |
while (el.firstChild) { | |
newEl.appendChild(el.firstChild); // *Moves* the child | |
} | |
// Copy the attributes | |
if (keepAttributes) { | |
for (var i = el.attributes.length - 1; i >= 0; --i) { | |
newEl.attributes.setNamedItem(el.attributes[i].cloneNode()); | |
} | |
} | |
// Replace it | |
el.parentNode.replaceChild(newEl, el); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment