Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Traverse the DOM hierarchy and return the first ancestor that has all/any css attributes that match the provided hash. Expects jQuery, but could be easily modified to work w/o. Main use for this is in Chrome dev tools to quickly find the parent of an element that's responsible for layout troubles.
//
// Traverse the DOM hierarchy and return the first ancestor that has all/any
// css attributes that match the provided attribute:regexp hash.
//
var $parent = (function declares(el, attrs, any) {
var $el = $(el), fn = (!!any ? 'some' : 'every'), match;
if(!attrs || !$el.length || $el.is(document)) return undefined;
match = Object.keys(attrs)[fn](function(key) {
var css = $el.css(key), matcher = attrs[key];
if(matcher === '*' && css !== undefined) return true;
(matcher instanceof RegExp) || (matcher = new RegExp(matcher, 'i'));
return matcher.test(css);
});
return match ? $el : declares($el.parent(), attrs, any);
})($('.deep-in-the-weeds'), {'overflow': /(hidden)|(auto)/i});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment