Net-informations.com
SiteMap  | About    

find() Vs. closest() in jquery



The jQuery .find and .closest selectors are complements of each other and used together are the best way to get to the corresponding element of where the event occurred.

jQuery .find()

jQuery .find() get the descendants of each element in the current set of matched elements, filtered by a selector, Query object j, or element. This method going down the tree looking in the childs, and the childs of childs.

example

In the above code, the find() method search the decedent of the firstSelector element and return all elements that match secondSelector.

jQuery .closest()

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 . This method will go up the tree, into the parents, including the current element. The returned jQuery object contains zero or one element for each element in the original set

example

In the above code, the closest() method selects the element firstSelector and then traverses the dom upwards and returns the first element that matches the secondSelector

Both will first test the initial element before going through parent/child elements.










net-informations.com (C) 2019    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.