Reputation: 23
I have approximately such structure:
<div class='container'>
<div class='element' data-id='1'></div>
<div class='element' data-id='2'></div>
<div class='element' data-id='2'></div>
</div>
Where .element
s' are rendered dynamically.
So I wrote handler for these elements:
jQuery('.container').on('click', '.element', function () { //code })
But I need to do something with element, which was clicked.
How could I get clicked element?
Upvotes: 2
Views: 417
Reputation: 15685
HTML:
<div class='container'>
<div class='element' data-id='1'/>
<div class='element' data-id='2'/>
<div class='element' data-id='2'/>
</div>
Javascript:
$(function () {
$('.container').on('click', '.element', function () {
$clickedElement = $(this);
$data-id = $clickedElement.attr('data-id');
});
});
Upvotes: 0
Reputation: 15213
You have to do something with the target of the event.
Something like :
jQuery('.container').on('click', '.element', function (event) {
var clickedelement = $(event.target);
//code
})
Upvotes: 1
Reputation: 338128
The clicked element will be this
in your event handler function.
jQuery('.container').on('click', '.element', function () {
// use "this" or "jQuery(this)", depending on your needs
})
Note that this
will point to a DOM element, in your case a <div>
.
Upvotes: 6