Search code examples
javascriptjqueryrevealing-module-pattern

Getting element ID from dynamic element using Revealing Module Pattern


I have a module that created some elements dynamically. Since they are created dynamically, I am having bind events using the static element $('#data-container) containing the dynamically created elements like so:

var $dataContainer = $('#data-container');
var $deleteProject = $('.delete-project');
$dataContainer.on('click', $deleteProject, _deleteProject);

Sooo.... I cannot use $(this) to get the ID if the button that I clicked. The context is #data-container and not the actual button that I clicked. I should also add that So, how can I do this? Here is my full code for better understanding:

var $dataContainer = $('#data-container'); // Container holding dynamic elements
var $deleteProject = $('.delete-project'); // Delete buttons for elements

$dataContainer.on('click', $deleteProject, _deleteProject);

function _deleteProject(){
  var project = $(this).attr('id'); // Doesn't work
  console.log(project);
}

Solution

  • You can get the ID from the event argument. Try this. The event should always contain which target was clicked.

    function _deleteProject(event){
      var id = event.target.id;
      var project = $(this).attr('id'); // Doesn't work
      console.log(project);
    }