Skip to content

Instantly share code, notes, and snippets.

@matesnippets
Created February 23, 2015 20:00
Show Gist options
  • Select an option

  • Save matesnippets/5cf80e054cb574f03215 to your computer and use it in GitHub Desktop.

Select an option

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.
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;
}
});
@taheri24

Copy link
Copy Markdown

@luispmoraisc

Copy link
Copy Markdown

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