Simply use the .closest()
method: $(this).closest('.li').remove();
It starts with the current element and then climbs up the chain looking for a matching element and stops as soon as it found one.
.parent()
only accesses the direct parent of the element, i.e. div.msg-modification
which does not match .li
. So it never reaches the element you are looking for.
Another solution besides .closest()
(which checks the current element and then climbs up the chain) would be using .parents()
- however, this would have the caveat that it does not stop as soon as it finds a matching element (and it doesn't check the current element but only parent elements). In your case it doesn't really matter but for what you are trying to do .closest()
is the most appropriate method.
Another important thing:
NEVER use the same ID for more than one element. It's not allowed and causes very hard-to-debug problems. Remove the id="191"
from the link and, if you need to access the ID in the click handler, use $(this).closest('.li').attr('id')
. Actually it would be even cleaner if you used data-id="123"
and then .data('id')
instead of .attr('id')
to access it (so your element ID does not need to resemble whatever ID the (database?) row has)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…