Skip to content

Instantly share code, notes, and snippets.

@mikedamage
Created March 31, 2014 20:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikedamage/9901946 to your computer and use it in GitHub Desktop.
Save mikedamage/9901946 to your computer and use it in GitHub Desktop.
Ancestry climber plugin in plain JS
/*
jQuery Ancestry Climber Plugin
Defines a class that traces an element's ancestry, executing
a callback on each ancestor.
*/
(function() {
var AncestryClimber;
AncestryClimber = (function() {
function AncestryClimber(elem, callback) {
this.elem = elem;
this.callback = callback != null ? callback : $.noop;
if (!this.elem) {
throw new Error('Please supply a DOM element');
}
if (!this.callback) {
throw new Error('Please supply a callback function');
}
this.$elem = $(this.elem);
this.iterations = 0;
}
AncestryClimber.prototype.climbLevel = function(skipStop) {
var $parent, stop;
if (skipStop == null) {
skipStop = true;
}
this.iterations += 1;
$parent = this.$elem.parent();
stop = this.callback.call(this.$elem, this.iterations) === false;
if (skipStop) {
stop = false;
}
this.$elem = $parent;
if (!stop && $parent[0].nodeName !== '#document') {
return this.climbLevel(false);
}
};
return AncestryClimber;
})();
if (typeof jQuery === 'undefined') {
return window.AncestryClimber = AncestryClimber;
}
$.fn.extend({
climbAncestry: function(cb) {
var climber;
climber = new AncestryClimber($(this), cb);
climber.climbLevel();
return this;
}
});
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment