0

This is prob a quite weird or simple error. But it's doing my head in lol. The code below is a click event handler aimed at 2 <img> elements. You click on the one <img> element classed "undo" - This should remove the <img> being clicked and also the element classed "bin" directly next to it at the same time. I manage to either the one or the other removed but not both. Can anyone help please? Thank you Walter

JS:

$('ul').on('click','.undo',function(e) {
    $(this).remove();   
    $(this).prev().remove();

HTML:

<img src="images/bin.png" align="right" class="bin">
<img src="images/undo.png" align="right" class="undo">
Rino Raj
  • 6,264
  • 2
  • 27
  • 42
Walter
  • 1
  • 1
  • 3

3 Answers3

0

Once you call $(this).remove();, the element is removed from the dom, thereafter $(this).prev() will not find any element as there won't be any previous sibling for the detached element

$('ul').on('click', '.undo', function (e) {
    $(this).prev().addBack().remove();

Or

$('ul').on('click', '.undo', function (e) {
    $(this).prev().remove();
    $(this).remove();
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • That's what I argued to myself as well. I tried both your suggestion but no avail. Thanks for you input. – Walter Jul 21 '15 at 07:22
  • @Walter see https://jsfiddle.net/arunpjohny/qxgd7ut8/1/ - can you reproduce the problem in the fiddle – Arun P Johny Jul 21 '15 at 07:45
  • Thanks Johny, All sorted now. I can confirm it was to do with the bubbling effect which triggered another click event interfering. – Walter Jul 22 '15 at 08:07
0

Swap the removal process instead as below:

$('ul').on('click','.undo',function(e) {
    $(this).prev().remove(); 
    $(this).remove();   
});

DEMO

What you are doing here is trying to remove the previous element once the current element has been removed and jquery will not be able to find this element once removed, to remove its previous element. So just remove its previous element first and then remove the current element.

Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
  • I have tried swapping around but then nothing happens. Both elements stays on the screen. This which doesn't make sense to me – Walter Jul 21 '15 at 07:21
  • have you tried the **[DEMO](https://jsfiddle.net/Guruprasad_Rao/k20kL4r5/)**. If that doesn't work for you in your system then you might need to copy the whole piece of code so that we can understand the problem properly! – Guruprasad J Rao Jul 21 '15 at 07:32
0

I played around with the rest of my code and realised the problem lies there. The problem comes in with bubbling effect and that the items were added after the page loaded via the DOM.

Thanks for looking into - I need to go analyse other bits of my code causing this not to work.

Walter
  • 1
  • 1
  • 3