0

I know this question has been answered a lot, but when I applied this solution Event binding on dynamically created elements? the selector selects all the elements and retrieved only the first element

$('body').on('click','a.delete',function() {
   var id = $('a.delete').attr('id');
   var par = $('a.delete').closest('.foo');
   console.log(id);
   par.hide();
   postDelete(id);
});

.foo is a parent element of a.delete
this code hides all elements with class .foo and delete the first element with class a.delete not the clicked one

How can I retrieve the ID of the element I clicked and hide its parent?

Community
  • 1
  • 1
Beshoy Tamry
  • 75
  • 1
  • 11

2 Answers2

0

You should use this instead of a.delete in click event to get the reference of clicked a.delete like following.

$('body').on('click', 'a.delete', function () {
    var id = $(this).attr('id'); //change here
    var par = $(this).closest('.foo'); //change here
    console.log(id);
    par.hide();
    postDelete(id);
})
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
0

Use this to get the clicked element.

From the docs, In addition to the event object, the event handling function also has access to the DOM element that the handler was bound to via the keyword this

$('body').on('click', 'a.delete', function() {
  var id = $(this).attr('id');
  var par = $(this).closest('.foo');
  console.log(id);
  par.hide();
  postDelete(id);
});
Rayon
  • 36,219
  • 4
  • 49
  • 76