Skip to content

Instantly share code, notes, and snippets.

@tomfordweb
Created March 21, 2018 17:15
Show Gist options
  • Save tomfordweb/95e2270d979708f0640afa3de2726e21 to your computer and use it in GitHub Desktop.
Save tomfordweb/95e2270d979708f0640afa3de2726e21 to your computer and use it in GitHub Desktop.
Add attributes to Element
/**
* Pass an object of attributes and their values and the element to modify
* @param {object} attributes Key-value pairs consisting of the attribute, and it's value
* @param {DOM Elem} element A queried or generated dom element
*/
function addAttributesToElement(attributes, element) {
for(var key in attributes) {
if (attributes.hasOwnProperty(key)) {
var attrKey = document.createAttribute(key);
attrKey.value = attributes[key];
element.setAttributeNode(attrKey);
}
}
return element;
}
// usage
var row = addAttributeToElement({'class' : 'gallery-page', 'id' : 'test'}, document.createElement('div'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment