jquery closest bug for same class

26 Views Asked by At

ul alt2 should be aaa3 but becomes aaa0 why?

$(" .item").each(function(e){
  tt=$(this);
  tt.attr("alt",e);
  $(this).closest('.item').attr('alt2', 'aaa'+$(this).attr('alt')  );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<ul class='item' alt2=''>
  <li class='item'>aaaa</li>
  <li class='item'>aaaa</li>
  <li class='item'>aaaa</li>
</ul>

ul alt2 should be aaa3 but becomes aaa0 why?

1

There are 1 best solutions below

0
David On

Not a bug in .closest(), but I suppose it could be unintuitive. Look closely at the description in the documentation (emphasis mine):

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.

In this case the element itself is matching the selector:

$(this).closest('.item')

You could use .parents instead:

$(this).parents('.item')

Or use a more specific selector:

$(this).closest('ul.item')