Created
August 12, 2013 00:06
-
-
Save OliDM/6207469 to your computer and use it in GitHub Desktop.
Wrap a given element in a given type of element
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
// wrapelement.js | |
// https://github.com/bgrins/devtools-snippets | |
// Wrap a given element in a given type of element | |
// wrapElement('.foo', 'h1'); | |
// wrapElement(document.querySelector('#bar'), 'div'); | |
// | |
// LICENSE: [MIT](http://gkatsev.mit-license.org) | |
(function() { | |
window.wrapElement = function(el, whatToWrapIn) { | |
var newParent = document.createElement(whatToWrapIn), | |
oldParent, | |
nextSibling; | |
if (typeof el === 'string') { | |
el = document.querySelector(el); | |
} | |
oldParent = el.parentNode; | |
nextSibling = el.nextSibling; | |
newParent.appendChild(el); | |
if (nextSibling) { | |
oldParent.insertBefore(newParent, nextSibling); | |
} else { | |
oldParent.appendChild(newParent); | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment