Skip to content

Instantly share code, notes, and snippets.

@john-doherty
Created August 29, 2020 14:20
Show Gist options
  • Save john-doherty/c0fd172d81c9585a952e5e3ecaedc6ed to your computer and use it in GitHub Desktop.
Save john-doherty/c0fd172d81c9585a952e5e3ecaedc6ed to your computer and use it in GitHub Desktop.
Gets attribute off HTML element or nearest parent
/**
* Gets attribute off HTML element or nearest parent
* @param {object} el - HTML element to retrieve attribute from
* @param {string} attributeName - name of the attribute
* @param {any} defaultValue - default value to return if no match found
* @returns {any} attribute value or defaultValue
*/
function getNearestAttribute(el, attributeName, defaultValue) {
// walk up the dom tree looking for data-action and data-trigger
while (el && el !== document.documentElement) {
var attributeValue = el.getAttribute(attributeName);
if (attributeValue) {
return attributeValue;
}
el = el.parentNode;
}
return defaultValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment