http://jsfiddle.net/3Bvt9/3/
HTML
<div id="div1">
<img class="size" src="">
<input name="rdo" id="rdo" type="radio" value="1">
<div id="div2">
<label>radiobutton</label>
<div id="div3">
<a href="javascript:void(0)">link</a>
<input name="abc" id="abc" type="hidden" value="1">
</div>
</div>
</div>
jquery
$('#abc').parent().parent().parent().find("input[type='radio']").length; //1
$('#abc').closest("input[type='radio']").length; //0 why?
Why doesn't the closest query work? I thought closest() traverses up through its ancestors in the DOM tree.
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.
jQuery parent() Method The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree.
This is because input[type="radio"]
is not a parent of #abc
, rather it's a sibling of the grandparent element.
Also, according to w3c, <input>
elements can't have child elements, unlike <button>
, i.e. it doesn't "wrap" around #abc
.
The first method works because $('#abc').parent().parent().parent()
points to the top <div>
; doing .find("input[type='radio']")
on that will find the radio button as its child element.
This would also work:
$('#abc').parent().parent().siblings('input[type="radio"]).length; // 1
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