Last Updated: February 25, 2016
·
2.378K
· magalhini

foo.closest(bar) for Mootools

element.closest() for MooTools

Here's a sample implementation of the 'closest()' jQuery method, but for MooTools. It takes your first element and them iterates over its own parent until it finds the element you're looking for, returning it.

Code

Element.implement({
    closest: function(el) {
        var find = this.getElement(el),
            self = this;

        while (self && !find) {
            self = self.getParent();
            find = self ? self.getElement(el) : null;
        }

        return find;
    }
});

Usage

var myEl = document.getElement('.foo');
var findUl = myEl.closest('ul');

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside