Well, as the title says, I'm trying to remove elements that I add to a div with .append
but I can't.
The .append
$("#elPedido").append('<div class="lineasComanda">\
<div class="row" style="margin: 0px;">\
<div class="col-2 center" style="padding: 0px;">\
<img src="'+ resultProNormal.productNormal.foto +'" alt="" class="imgComanda">\
</div>\
<div class="col-5" style="padding: 0px;">\
<h2>'+ resultProNormal.productNormal.name +'</h2>\
<small>Familiar</small>\
</div>\
<div class="col-1" style="padding: 0px;">\
<h5>x1</h5>\
</div>\
<div class="col-2 txtRight" style="padding: 0px;">\
<h5>'+ resultProNormal.productNormal.precio +'€</h5>\
</div>\
<div class="col-2 center" style="padding: 0px;">\
<div class="deleteFila"><a class="delete"><i class="far fa-trash-alt"></i></a></div>\
</div>\
</div>\
</div>');
The function to remove
$("body").on("click",".deleteFila", function(){
var indice = $(".deleteFila").index(this);
console.log(indice);
//carrito.splice(indice, 1);
$(this).parent(".lineasComanda").remove();
});
If it brings me the console.log(indice)
index correctly, that is, the function is working. If, on the contrary, append
I remove all of .div row
them and cols
leave only one div inside of lineasComanda
it, it eliminates it without problems.
I don't know how to get me to catch all those divs.
Cheers
Edition
I have solved it like this but I don't know if it is right because I don't understand why it works like that.
$(this).closest(".lineasComanda").remove();
Given your HTML structure, the call
$(this).parent(".lineasComanda")
can't work because the function.parent()
looks for the immediate parent, and in this case the div.lineasComanda
isn't, since the div.row
gets between them.$(this).closest(".lineasComanda")
is correct in this case, since the function.closest()
looks for the closest parent that meets the indicated conditions, so it skips the parent.row
(because it does not meet them) and manages to reach the.lineasComanda
.