Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if class exists somewhere in parent

Tags:

javascript

dom

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 library, just vanilla JS.

In the examples below it should return true if the element in question resides somewhere in the childs of an element with "the-class" as the class name.

I think it would be something like this with jQuery:

if( $('#the-element').parents().hasClass('the-class') ) {     return true; } 

So this returns true:

<div>     <div class="the-class">         <div id="the-element"></div>     </div> </div> 

So does this:

<div class="the-class">     <div>         <div id="the-element"></div>     </div> </div> 

...but this returns false:

<div>     <div class="the-class">     </div>     <div id="the-element"></div> </div> 
like image 456
user2143356 Avatar asked May 31 '13 18:05

user2143356


People also ask

What is the difference between parentNode and parentElement?

parentNode gives the parent, while . parentElement gives undefined.

Is element child of jQuery?

children() is an inbuilt method in jQuery which is used to find all the children element related to that selected element. This children() method in jQuery traverse down to a single level of the selected element and return all elements.


2 Answers

You'll have to do it recursively :

// returns true if the element or one of its parents has the class classname function hasSomeParentTheClass(element, classname) {     if (element.className.split(' ').indexOf(classname)>=0) return true;     return element.parentNode && hasSomeParentTheClass(element.parentNode, classname); } 

Demonstration (open the console to see true)

like image 110
Denys Séguret Avatar answered Sep 20 '22 17:09

Denys Séguret


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>
like image 36
a.robert Avatar answered Sep 20 '22 17:09

a.robert