-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,635
  • 3
  • 31
  • 55

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,987
  • 13
  • 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
  • 270,417
  • 55
  • 406
  • 400
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
  • 53,868
  • 5
  • 73
  • 87