Kaetana
Kaetana

Reputation: 23

How to specify dynamic element in javascript on() function?

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 .elements' 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

Answers (3)

JohnJohnGa
JohnJohnGa

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

putvande
putvande

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

Tomalak
Tomalak

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

Related Questions