Skip to content

Instantly share code, notes, and snippets.

@doubleedesign
Created March 27, 2018 01:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doubleedesign/541023a61a81d940cbb0184f81dad7f6 to your computer and use it in GitHub Desktop.
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
/**
* 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);
};
/**
* 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