duyn9uyen
duyn9uyen

Reputation: 10311

jQuery can't get .closest() to search up DOM tree

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.

Upvotes: 9

Views: 4600

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173552

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

Upvotes: 14

Related Questions