Created
March 27, 2018 01:48
-
-
Save doubleedesign/541023a61a81d940cbb0184f81dad7f6 to your computer and use it in GitHub Desktop.
Wrap an element in a specified tag with specified classes, using vanilla JavaScript
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
/** | |
* Wrap an element | |
* @param elementToWrap - selector of element to wrap | |
* @param elementToUse - HTML tag to use for the wrapper | |
* @param classes - class(es) to add; accepts string or array | |
* @returns {Node | *} | |
*/ | |
function wrapThis(elementToWrap, elementToUse, classes) { | |
var wrapper = document.createElement(elementToUse); | |
elementToWrap.parentNode.appendChild(wrapper); | |
console.log(typeof(classes)); | |
if(typeof(classes) == 'string') { | |
wrapper.classList.add(classes); | |
} else { // It's an array | |
for (var i = 0; i < classes.length; i++) { | |
wrapper.classList.add(classes[i]); | |
} | |
} | |
return wrapper.appendChild(elementToWrap); | |
}; |
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
/** | |
* Add wrappers to YouTube and Vimeo embeds | |
* @uses wrapThis() | |
*/ | |
// Select all the embeds | |
var embeds = document.querySelectorAll('iframe[src*="youtube.com"], iframe[src*="vimeo.com"]'), i; | |
// Define classes. Must be an array/object if sending multiple classes; can use a string if only sending one class | |
var classes = ['responsive-embed', 'widescreen']; | |
// Loop through all the embeds and run the wrapThis() function on each | |
for (i = 0; i < embeds.length; i++) { | |
wrapThis(embeds[i], 'div', classes); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment