How to call function on click event in Jquery when the element is generated dynamically by script and access through class selector?

Viewed 39

I am generating an anchor tag through script with class 'section-delete-btn' :

<a class='section-delete-btn' role='button' id = '" + $("#section_name").val() + "'href='#'><i class='section-delete-btns fa fa-trash-o' aria-hidden='true'></i></a>

I am trying to access the a tag through class selector like this :

//delete a section
$('a').on('click','.section-delete-btn',function(){
  //get section name
  var section_name = $(this).attr('id');
  alert(section_name);
});
1 Answers

You are already using a delegate listener, but it will fail if, at the time of attaching the listener, your document does not have any a elements. Instead, use document:

$(document).on('click','a.section-delete-btn',function(){
  //get section name
  var section_name = $(this).attr('id');
  alert(section_name);
});
Related