Is there an equivalent to .closest() that searches down the DOM tree instead of up?

后端 未结 6 1254
失恋的感觉
失恋的感觉 2020-12-20 11:15

Is there an equivalent to .closest() that searches down the DOM tree instead of up?

相关标签:
6条回答
  • 2020-12-20 11:18

    The closest method does actually search down the tree (despite what the documentation says), but I know what you mean. You want one that searches among the children of the element. Depending on how you want to search:

    $('#Id').children('div');
    

    or

    $('#Id').find('div');
    
    0 讨论(0)
  • 2020-12-20 11:18

    Closest is searching UP related to the documentations "For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree" and as you can see "The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well". I did not found a good solution for closest down the tree because the good thing about closest is that its stop searching elements when it find the first matched selector and find continue searching. So what you can do is to use the .first() filter.

    $('selector').first();
    

    OR

    obj.find('selector').first();
    

    It will find a match of multiple element but will return only the first element like closest but less performance.

    https://api.jquery.com/first/

    0 讨论(0)
  • 2020-12-20 11:20

    You can use find() method. And get the first element from resulting set.

    0 讨论(0)
  • 2020-12-20 11:31

    No, not with jQuery. But with pure DOM, there is for single elements:

    $($element[0].querySelector('.whatever'))
    

    Pick the first (and only?) element from your selection, run the “DOM .find()” and wrap it up again.

    Compared to the other answers here, this is the only (short) way to stop wasting CPU cycles after finding the first match.—It leaves me, once again, with a bitter aftertaste of the thoughtfulness in jQuery. The DOM feels incomplete, too, no doubt, but at least they have the shortcut version of .querySelectorAll().

    0 讨论(0)
  • 2020-12-20 11:33

    $('#Id div:first') does also what you are looking for.

    Please also note that while closest() only returns one element, find(), children() and also $("#Id div") returns all matching elements, so you must add .first() or :first to reduce the result to the first occurence.

    0 讨论(0)
  • 2020-12-20 11:37

    In case somebody needs to search UP, it's easy with .parents() method.

    You can leave it empty, or specify selectors like .parents("div").

    0 讨论(0)
提交回复
热议问题