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?
Not a bug in
.closest(), but I suppose it could be unintuitive. Look closely at the description in the documentation (emphasis mine):In this case the element itself is matching the selector:
You could use
.parentsinstead:Or use a more specific selector: