I\'m really struggling to see how to do this. I want to check if a class exsits somewhere in one of the parent elements of an element.
I don\'t want to use any libra
I believe if( $('#the-element').parents('.the-class').length )
to be more efficient, but perhaps not as human-readable; which, with querySelector
in the picture, could be replaced with the following method:
function hasParent(element, parentSelector) {
var potentialParents = document.querySelectorAll(parentSelector);
for(i in potentialParents) if(potentialParents[i].contains(element))
return potentialParents[i];
return false;
}
That'd give you the ability to do:
var elm = document.getElementById('the-element');
if(hasParent(elm, '.the-class')) return true;
You can use some
and contains
to achieve the result:
function hasParentWithMatchingSelector (target, selector) {
return [...document.querySelectorAll(selector)].some(el =>
el !== target && el.contains(target)
)
}
// usage
hasParentWithMatchingSelector(myElement, '.some-class-name');
I'm ok with the function that Denys Séguret posted, it looks elegant and I like it.
I just tweaked a little bit that function since if the class specified in the parameter, is not present in the whole DOM, it fails when the recursion reaches the document object because is true that we control if the element has the parent node (in the last line, and when the document is the element the parent node is null) but before we execute the previous line, and when the element is the document, document.className
is undefined
and it fails, so the control must be moved to the top.
function hasSomeParentTheClass(element, classname) {
//
// If we are here we didn't find the searched class in any parents node
//
if (!element.parentNode) return false;
//
// If the current node has the class return true, otherwise we will search
// it in the parent node
//
if (element.className.split(' ').indexOf(classname)>=0) return true;
return hasSomeParentTheClass(element.parentNode, classname);
}
You can use the closest()
method of Element
that traverses parents (heading toward the document root) of the Element until it finds a node that matches the provided selectorString. Will return itself or the matching ancestor. If no such element exists, it returns null.
You can convert the returned value into boolean
const el = document.getElementById('div-03');
const r1 = el.closest("#div-02");
console.log(Boolean(r1));
// returns the element with the id=div-02
const r2 = el.closest("#div-not-exists");
console.log(Boolean(r2));
<article>
<div id="div-01">Here is div-01
<div id="div-02">Here is div-02
<div id="div-03">Here is div-03</div>
</div>
</div>
</article>