Check with Javascript or jquery if the parent div of a div contains a specific class name

I have a text in a set of divs. If somebody clicks on that text I have to know if the 4th parent div with the class "div1" holds the class name "exampleclass".

My HTML:

<div class="div1 exampleclass">
  <div class="div2">
    <div class="div3">
      <div class="div4">
        <div class="5">
          Text
        </div>
      </div>
    </div>
  </div>
</div>

 <div class="div1">
  <div class="div2">
    <div class="div3">
      <div class="div4">
        <div class="5">
          Text
        </div>
      </div>
    </div>
  </div>
</div>

<div class="div1">
  <div class="div2">
    <div class="div3">
      <div class="div4">
        <div class="5">
          Text
        </div>
      </div>
    </div>
  </div>
</div>

I tried to find this out with the following jquery/javascript:

if ($(this).closest('.div1').classList.contains('exampleclass') {
  console.log ('found');
}

It would work, when I could work with id's, but I cant because the id's are random, and I don't know them before the site is loaded. Has anybody an idea how to solve this problem?

Upvotes: 0

Views: 37

Answers (2)

Nick
Nick

Reputation: 1629

I haven't testet but you can do

if(this.closest(".exampleclass")){
      console.log ('found');
}

because closest() return null if there isn't an ancestor with the .exampleclass selector

I used vanilla javascript but in jquery is very similar

Upvotes: 0

cytek04
cytek04

Reputation: 596

classlist.contains is not a jQuery method. Use .hasClass().

if ($(this).closest('.div1').hasClass('exampleclass') {
  console.log ('found');
}

This should work. Cheers!

Upvotes: 1

Related Questions