Basically both methods used to find the element and both traverse up the DOM tree.
closest()
1. It start searches from the current element.2. This method travels up the DOM tree until it finds an element which match for the supplied selector.
3. It may return return zero or one element
parents()
1. It start searches from the parrent element.2. This method travels up the DOM tree and return all the element which match for the supplied selector.
3. It may return return zero, one or multiple element
CODE
<!DOCTYPE html> <html> <head> <title>jQuery With Example</title> <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $(".btnClosest").click(function () { $(this).closest('.dvTest').each(function () { alert('Closest: ' + $(this).html()); }); }); $(".btnParents").click(function () { $(this).parents('.dvTest').each(function () { alert('Parents: ' + $(this).html()); }); }); }); </script> </head> <body> <div class="Container"> <div class="dvTest"> <div class="dvTest"> <p>Click both button</p> <input type="button" class="btnClosest Button" value="Closest" /><br /><br /> <input type="button" class="btnParents Button" value="Parents" /> </div> </div> </div> </body> </html>
DISPLAY
Click both button
It's actually a nice and useful piece of info. I'm
ReplyDeletehappy that you simply shared this helpful info with us.
Please keep us up to date like this. Thank you for sharing.