jQuery Events Events for repeating elements without using ID's


Example

Problem

There is a series of repeating elements in page that you need to know which one an event occurred on to do something with that specific instance.

Solution

  • Give all common elements a common class
  • Apply event listener to a class. this inside event handler is the matching selector element the event occurred on
  • Traverse to outer most repeating container for that instance by starting at this
  • Use find() within that container to isolate other elements specific to that instance

HTML

<div class="item-wrapper" data-item_id="346">
   <div class="item"><span class="person">Fred</span></div>
   <div class="item-toolbar">
      <button class="delete">Delete</button>
   </div>   
</div>
<div class="item-wrapper" data-item_id="393">
   <div clss="item"><span class="person">Wilma</span></div>
   <div class="item-toolbar">
      <button class="delete">Delete</button>
   </div>   
</div>

jQuery

$(function() {
  $('.delete').on('click', function() {
    // "this" is element event occured on
    var $btn = $(this);
    // traverse to wrapper container
    var $itemWrap = $btn.closest('.item-wrapper');
    // look within wrapper to get person for this button instance
    var person = $itemWrap.find('.person').text();
    // send delete to server and remove from page on success of ajax
    $.post('url/string', { id: $itemWrap.data('item_id')}).done(function(response) {
      $itemWrap.remove()
    }).fail(function() {
      alert('Ooops, not deleted at server');
    });
  });
});