The requested URL was not found on this server. Show Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. Apache/2.4.41 (Ubuntu) Server at proveedores.yaguar.com.ar Port 443 With jQuery you can traverse up the DOM tree to find ancestors of an element. An ancestor is a parent, grandparent, great-grandparent, and so on. Traversing Up the DOM TreeThree useful jQuery methods for traversing up the DOM tree are:
jQuery parent() MethodThe This method only traverse a single level up the DOM tree. The following example returns the direct parent element of each jQuery parents() MethodThe The following example returns all ancestors of all You can also use an optional parameter to filter the search for ancestors. The following example
returns all ancestors of all jQuery parentsUntil() MethodThe The following example returns all ancestor elements between a Example $(document).ready(function(){ Try it Yourself » jQuery ExercisesTest Yourself With ExercisesExercise:Use a jQuery method to get the direct parent of a <span> element. Start the Exercise jQuery Traversing ReferenceFor a complete overview of all jQuery Traversing methods, please go to our jQuery Traversing Reference. Last year, I wrote about my preferred approach to event delegation. Specifically, I prefer to attach my delegated event handlers to the closest common ancestor of two or more elements. Although I don't use jQuery, the following snippet from the documentation for the Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of I normally just find the common ancestor manually, but I thought "hey, wouldn't it be cool if I could write a helper function to do this for me?" Over the weekend, that's exactly what I did. If you just want the helper function, here it is:
You can view a couple of demos on CodePen:
If you want to learn how it works, read on. Getting the matching elementsThe first thing we do is use the If there are no matching elements, we just return If there's only one matching element, then there's no point in using event delegation, so we just return it. That way, you can attach the event listener directly to the element and not bother with event delegation. Getting the common ancestorIf there are at least two elements, then we want to get their common ancestor. To do that, we can use the We create a
We want to start the range at the beginning of the first element, and stop the range at the end of the last element. The
For the first element, we pass the following to
For the last element, we pass the following to
Finally, now that the |