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

后端 未结 6 1274
失恋的感觉
失恋的感觉 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

    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/

提交回复
热议问题