closest() can only return a maximum of one element.
closest() will actually include the currently selected element in its filtering.
parents() gets all parents and then filters on your optional selector.
Try the following example:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title></title> </head> <body> <!-- Nested Div(s) --> <div id="parent3"> <div id="parent2"> <div id="parent1"> <div id="parent0"> <div id="LastInChain"></div> </div> </div> </div> </div>
<script> (function ($) { alert($('#LastInChain').parents().length); alert($('#LastInChain').parent().attr('id')); alert($('#LastInChain').parents('#parent0').attr('id')); alert($('#LastInChain').parents()[0].id);
alert($('#LastInChain').closest('#parent1').length); alert($('#LastInChain').closest('#parent1').length); alert($('#LastInChain').closest('#parent1').attr('id')); })(jQuery); </script>
</body> </html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title></title> </head> <body> <!-- Nested Div(s) --> <div id="parent3"> <div id="parent2"> <div id="parent1"> <div id="parent0"> <div id="LastInChain"></div> </div> </div> </div> </div>
<script> (function ($) { alert($('#LastInChain').parents().length); alert($('#LastInChain').parent().attr('id')); alert($('#LastInChain').parents('#parent0').attr('id')); alert($('#LastInChain').parents()[0].id);
alert($('#LastInChain').closest('#parent1').length); alert($('#LastInChain').closest('#parent1').length); alert($('#LastInChain').closest('#parent1').attr('id')); })(jQuery); </script>
</body> </html>
No comments:
Post a Comment