What's the difference between .closest() and .parents('selector')?

前端 未结 3 1861
囚心锁ツ
囚心锁ツ 2021-02-13 12:41

What\'s the difference between these? Is one more efficient than the other? I\'m a little bit confused to why they both exist. Say I have this markup:



        
3条回答
  •  渐次进展
    2021-02-13 13:12

    (Note: The question was edited the day after being asked, changing the question from about parent to being about parents [note the plural]. Which kind of makes a difference!)

    Re your original question about parent (singular) vs. closest: parent only ever goes one level up. closest starts with the current element (not just the parent) and keeps searching through ancestors until it finds a match (or runs out of ancestors).

    Re your updated question about parents (plural) vs. closest: There are two differences:

    1. Whether the current element is considered (it is with closest, it is not with parents).

    2. Whether the search stops with the first match (it does with closest, it doesn't with parents).

    From your original question:

    From the tags I could use either $(this).closest('tr'); or $(this).parent('tr');

    No, actually. $(this).parent('tr'); would return an empty jQuery object, because the parent of the span doesn't match the selector.

    From your updated question:

    From the tags I could use either $(this).closest('tr'); or $(this).parents('tr');

    You could, provided that your tr isn't also within another tr (e.g., a table containing a table). If that's the case, you'll get the same result. But if you have a table within a table, with parents you'll get multiple trs (all of the ancestor tr elements).

    Consider this structure:

    Testing 1 2 3

    If we hook click on the span, this is what we get back from the three relevant methods:

    • $(this).parent('div') - Empty jQuery object, the parent of the span is not a div.
    • $(this).parents('div') - jQuery object with two divs in it, the "inner" and "wrapper" divs (in that order).
    • $(this).closest('div') - jQuery object with one div in it, the "inner" one.

    Here's the result if we hook click on the span and use span as the selector:

    • $(this).parent('span') - Empty jQuery object, the parent of the span is not a span.
    • $(this).parents('span') - Empty jQuery object, the span has no ancestor spans.
    • $(this).closest('span') - jQuery object with the span that was clicked.

提交回复
热议问题