Created
December 14, 2019 22:13
-
-
Save jeffchiou/66db487d15b03a82208881112ce26458 to your computer and use it in GitHub Desktop.
Wrapping an Element with Another, using modern JS and compatible JS
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
/** | |
* 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