Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

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

This should work. Cheers!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading