Created
August 3, 2021 12:12
-
-
Save barneycarroll/0c0c17713f1c4812efc319fc183532ae to your computer and use it in GitHub Desktop.
Replace an element with a new one that has a different tagName
This file contains 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
export default function changeTag(original, tagName){ | |
// Create a replacement tag of the desired type | |
const replacement = document.createElement(tagName) | |
// Grab all of the original's attributes, and pass them to the replacement | |
Array.prototype.forEach.call(original.attributes, ({name, value}) => { | |
replacement.setAttribute(name, value) | |
}) | |
// Persist contents | |
replacement.append(...original.childNodes) | |
// Switch! | |
original.replaceWith(replacement) | |
return replacement | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment