user765368
user765368

Reputation: 20346

Find closest div that has a certain class

Let's say that I have some HTML like this:

<div>
    <div class="required another_class">
        <div class="some_class">
            <input type="checkbox" name="some_check" value="" />
        </div>
    </div>
</div>

How do I find the parent div of the checkbox that has the class required? As you can see above, the div has two classes required and another_class. Therefore something like this:

$(':checkbox').closest('div[class=required]');

Will not work. I thought I could do something like:

$(':checkbox').closest('div').hasClass('required');

But that doesn't work either.

Upvotes: 25

Views: 56734

Answers (2)

Pratik Goenka
Pratik Goenka

Reputation: 2369

Alternatively you can also use

$(':checkbox').parents('div.required')

Upvotes: 2

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

You can use CSS selector in .closest(), just like that :

$(':checkbox').closest('div.required');

Upvotes: 35

Related Questions