0

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
  • What are you trying to achieve? e is the index of the loop, since the ul is the first element of the selection e will be 0 in that case. Commented Apr 6, 2023 at 13:11

1 Answer 1

0

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.