1

I have a div with class c and I am adding some code to this class using Ajax so it ends up looking something like:

<div class="c">
  <div class="del" id="1"></div>
  <div class="del" id="2"></div>
  <div class="del" id="3"></div>
</div>

My class c is static and the divs with class delete are added using Ajax. Now what I want is to get the id of the div with class delete that I click on.

I was first doing:

$(".delete").click(function(){
    var id = $(this).attr('id');
    }
);

But this doesn't work. I later found out on SO that we should use .on() for content added using Ajax. From what I understood, I implemented it the following way:

$(".c").on('click','.delete',function(){
    var id = $(".delete").attr('id');
    }
);

But this gives me the id of the first delete. Could someone please provide a way so that i can get the id of the delete I clicked on assuming that the inner divs, namely:

<div class="del" id=i></div>

are added using Ajax. Thank you.

user4052205
  • 109
  • 1
  • 7

1 Answers1

1

You don't have to reselect .delete collection again with $('.delete'). .attr method invoked as getter on a collection of elements, returns an attribute value of the first element in collection. In your case you already have a reference to currently clicked element as this. Try this:

$(".c").on('click','.delete', function() {
    var id = this.id;
});

Also you can access id as HTMLElement property, so you don't need to read its attribute.

dfsq
  • 191,768
  • 25
  • 236
  • 258