Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find closest div that has a certain class

Tags:

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.

like image 775
user765368 Avatar asked Nov 08 '13 18:11

user765368


People also ask

What is .closest in Javascript?

The closest() method of the Element interface traverses the element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector.

How do you find the parent element of a class?

Use the closest() method to get the closest parent element by class, e.g. child. closest('. parent') . The closest() method traverses the Element and its parents until it finds a node that matches the provided selector.

How do I get the closest div using jquery?

The closest() method returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on. The DOM tree: This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.

How does closest work in jquery?

The closest( selector ) method works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression.


2 Answers

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

$(':checkbox').closest('div.required');
like image 102
Karl-André Gagnon Avatar answered Oct 20 '22 00:10

Karl-André Gagnon


Alternatively you can also use

$(':checkbox').parents('div.required')
like image 20
Pratik Goenka Avatar answered Oct 20 '22 00:10

Pratik Goenka