Skip to content

Instantly share code, notes, and snippets.

@roboshoes
Last active March 7, 2017 03:36
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save roboshoes/9519ccdf92333d78d9bf6ce5e2b1ffd8 to your computer and use it in GitHub Desktop.
Find attribute in node or parent.
// find attribute
export function findInParent( node, attribute, levels = Infinity ) {
return node.getAttribute( attribute ) ||
( levels > 0 ? findInParent( node.parentElement, attribute, --levels ) : null );
}
// find anything
export function findInParent( node, filter, levels = Infinity ) {
return filter( node ) ||
( levels > 0 ? findInParent( node.parentElement, filter, --levels ) : null );
}
@hapticdata
Copy link

It may be wiser to generalize this function's attribute parameter with a function

const findInParent = (n, iterator, levels=Infinity)=>
    iterator(n) || (levels > 0 ? findInParent(n.parentElement, iterator, levels - 1) : undefined);

findInParent(node, (n)=> n.getAttribute('data-name'))

@roboshoes
Copy link
Author

@hapticdata ... very wise Mr Data. Adjusted as suggested.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment