Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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.

like image 481
duyn9uyen Avatar asked May 23 '13 03:05

duyn9uyen


People also ask

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.

How do I find a specific parent in jQuery?

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.


1 Answers

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
like image 138
Ja͢ck Avatar answered Sep 28 '22 01:09

Ja͢ck