Skip to content

Instantly share code, notes, and snippets.

@jeffchiou
Created December 14, 2019 22:13
Show Gist options
  • Save jeffchiou/66db487d15b03a82208881112ce26458 to your computer and use it in GitHub Desktop.
Save jeffchiou/66db487d15b03a82208881112ce26458 to your computer and use it in GitHub Desktop.
Wrapping an Element with Another, using modern JS and compatible JS
/**
* Wrapper function with modern JS. May have issues with IE and Safari.
* Will preserve event handlers.
* @param {ChildNode} elToWrap The element you want to wrap.
* @param {ParentNode} wrapper The element to wrap with.
*/
const wrap = (elToWrap, wrapper) => {
elToWrap.before(wrapper) // so element doesn't move
wrapper.append(elToWrap) // automatically moves wrapped element.
}
/**
* More compatible wrapper function. Equivalent to the one found on
* https://plainjs.com/javascript/manipulation/wrap-an-html-structure-around-an-element-28/
* @param {Node} elToWrap The element you want to wrap.
* @param {Node} wrapper The element to wrap with.
*/
function oldWrap(elToWrap, wrapper) {
elToWrap.parentNode.insertBefore(wrapper, elToWrap)
wrapper.appendChild(elToWrap)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment