2

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?

1

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! So simple and evident answer and so helpful for me! Thanks for editing codestyle too.
1

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 
})

1 Comment

Sorry, re-reading OP question, i think here effectively event.target is what OP is looking for
0

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');
  });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.