-3

I added listener to element, which has been created dynamically - according to this - Jquery event handler not working on dynamic content [duplicate] .

But how can I get id of the element?

$(document.body).on('click', '.list-group-item', function(){  
var itemId=this.attr("id");  

This approach is wrong - the outcome is:

TypeError: this.attr is not a function

So in this case - how can I get id of my '.list-group-item' which has been clicked?

Community
  • 1
  • 1
kurumkan
  • 2,452
  • 3
  • 27
  • 53

3 Answers3

3

Use $(this).attr("id") to get id of element

$(document.body).on('click', '.list-group-item', function(){  
   var itemId = $(this).attr("id");  // update this
})
Jayesh Chitroda
  • 4,917
  • 12
  • 18
1

Try this syntax. You need to refrence this as $('this')

$(this).attr('id');

$(document.body).on('click', '.list-group-item', function(){  
     var itemId=$(this).attr("id");
}
Shubham Khatri
  • 246,420
  • 52
  • 367
  • 373
1

Inside the click callback function, this is the HTML element that was clicked

therefore, you can simply use

this.id;

or, if you prefer to use jQuery even when it isn't required

$(this).attr("id");
Jaromanda X
  • 1
  • 4
  • 64
  • 78