Created
August 29, 2020 14:20
-
-
Save john-doherty/c0fd172d81c9585a952e5e3ecaedc6ed to your computer and use it in GitHub Desktop.
Gets attribute off HTML element or nearest parent
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
/** | |
* 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