Skip to content

Instantly share code, notes, and snippets.

@Daniel-Hug
Last active November 12, 2021 02:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Daniel-Hug/d245b53b6195b9596c00659cb17cda6c to your computer and use it in GitHub Desktop.
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
// 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