Created
February 23, 2015 20:00
-
-
Save matesnippets/5cf80e054cb574f03215 to your computer and use it in GitHub Desktop.
JavaScript, Get closest element by class. Mimics the jQuery's `.closest()` with pure JavaScript.
This file contains hidden or 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
| define(function() { | |
| /** | |
| * Get the closest element of a given element by class | |
| * | |
| * Take an element (the firt param), and traverse the DOM upward from it | |
| * untill it hits the element with a given class name (second parameter). | |
| * This mimics jquery's `.closest()`. | |
| * | |
| * @param {element} el The element to start from | |
| * @param {string} clazz The class name | |
| * @return {element} The closest element | |
| */ | |
| return closestByClass = function(el, clazz) { | |
| while (el.className != clazz) { | |
| el = el.parentNode; | |
| if (!el) { | |
| return null; | |
| } | |
| } | |
| return el; | |
| } | |
| }); |
Hi matesnippets.
Thank you for your code. But I think line 14 should be: while(!el.classList.contains(clazz)) because if there are two classes, your code doesn't find the DOM object!!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
below link is better . http://stackoverflow.com/questions/18663941/finding-closest-element-without-jquery/38994356#38994356