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

前端 未结 3 1862
囚心锁ツ
囚心锁ツ 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:25

    parent returns the immediate parents (one for each element in the caller object) or nothing if the parent does not match the selector. closest returns the closest ancestor matching ancestor for each element (which can be the original element). The third similar function, parents, returns all matching ancestors (not including the element itself).

    Generally, closest is more resistant to refactoring the HTML code than parent, if you choose the selector sensibly.

提交回复
热议问题