Vincent Teyssier
Vincent Teyssier

Reputation: 2217

Different between parents() and closest parent()

I don't understand very well the difference, in the case that there is only one my_class class in the dependency tree, between :

$(this).parent().closest('.my_class').attr('id');

And

$(this).parents('.my_class').attr('id')

Is there actually any difference ?

EDIT: no this no duplicate as here I take the example of only one my_class in the dependency tree. I know that parent() returns only one element when parents() return the list of matching elements, and that closest() can return "this" if it matches the filter.

HTML example :

<div class="agenda_relative">
    <div class="agenda_day" data-date="<?php echo $year."-".$m."-".$d; ?>">
            <div class="agenda_day_nr"><?php echo $d; ?></div>      
               <ul class="agenda_hour">
                    <?php foreach ($date->hours as $h): ?>
                        <li><?php echo $h; ?><p class='agenda_hour_input' data-hour="<?php echo $h; ?>" contenteditable="true"></p>

On event blur on the I want to get the data('date') of the agenda_day div

I have the working solution, but I wonder if there is any difference between the 2 methods above

Upvotes: 0

Views: 86

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074666

Is there actually any difference ?

Not in the id value you get, no.

But although they get the same result, they do different things:

  • $(this).parent().closest(".my_class") builds three jQuery objects, the last of which has at most one element in it.

  • $(this).parents(".my_class") builds two jQuery objects, the last of which potentially has several elements in it, which are in order according to how close they are to this (the first entry is the nearest one). Of course, you've said that only one .my_class can exist in your scenario, so in your specific case you'll get at most one element there as well. But in the general case, even if there were nested my_class elements, you'd still get the right id.

There's also a difference in terms of how much traversal occurs: In the second case, even once it's found the parent, jQuery will still keep traversing up the ancestry looking for more of them (because although you know there aren't any more to find, jQuery doesn't, so it goes ahead and looks). In the first case, it'll stop with the first one it finds.

Upvotes: 1

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93581

Assuming that .my_class is not on the current element too, you actually just want:

$(this).closest('.my_class').attr('id');

The other two grab varying numbers of matching element (parent only gets the immediate parent element, parents gets all ancestors, closest stops on the first match).

Upvotes: 1

Related Questions