When writing JavaScript code for my own projects, this functionality is the singlemost used algorithm that does not already exist: Finding an ancestor element that has a certain HTML class.
Algorithm:
- Does the current element have a parent element?
- Yes: Continue with step 2
- No: There are no solutions to the task, return a null value
- Does the parent element of the current element have the required class?
- Yes: Return the parent element
- No: Set the current element to its parent element and repeat step 1
Code:
Element.prototype.getAncestorByClassName = function(className) {
var currentParent = this.parentElement
while (true) {
// If the root of the DOM is reached, an ancestor cannot be found anymore.
if (currentParent === null) {
return null
}
if (currentParent.classList.contains(className)) {
return currentParent
}
var currentParent = currentParent.parentElement
}
}
Notes:
- I want to be able to call
element.getAncestorByClassName("class-name")
hence the use ofElement.prototype
. Does this approach yield any problems? I am aware that I would override anygetAncestorByClassName()
functions that are introduced in future versions of ECMAScript - There are possibly multiple results for the task I specified. The algorithm will return the closest ancestor that has the given class.
- If there are no results,
null
is returned as other functions likegetElementById()
do the same. - Browser support should cover all modern browsers. I do not consider IE8–IE10 modern browsers. The lack of support for
classList
on these is noted but not essential to me right now.
.closest('.classname')
and polyfill it for the older browsers? \$\endgroup\$