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.
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.
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.
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.
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.
You can use CSS selector in .closest()
, just like that :
$(':checkbox').closest('div.required');
Alternatively you can also use
$(':checkbox').parents('div.required')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With