Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Created August 3, 2021 12:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barneycarroll/0c0c17713f1c4812efc319fc183532ae to your computer and use it in GitHub Desktop.
Save barneycarroll/0c0c17713f1c4812efc319fc183532ae to your computer and use it in GitHub Desktop.
Replace an element with a new one that has a different tagName
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