Mithc Mithc - 7 months ago 21
Javascript Question

How to access to the "first" selector of jQuery .on()?

What I'm trying is, having this script:

$('[data-foo]').on('click', '.button-action', function() {
// Show alert on $('.button-action', this).
// Alert message: Lorem ipsum {$('.foo-id', this).text()}

And I have multiple elements like this, that are generated dynamically:

<div data-foo="{id}>
<div class="foo-id">
Lorem Value
<button class="button-action">Click to show the id of this data-foo</button>

In other words, I want to access to
button I clicked.


You can use event.delegateTarget to access the element the handler is attached to ([data-foo] in this case):

$('[data-foo]').on('click', '.button-action', function(event) {

But if you always want to get foo-id and it's always the previous sibling, you can just use .prev() as well: