Mithc Mithc - 3 months ago 6
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
</div>
<button class="button-action">Click to show the id of this data-foo</button>
</div>


In other words, I want to access to
$('[data-foo]')
of
this
button I clicked.

Answer

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) {
    console.log($(event.delegateTarget).find('.foo-id').text());
});

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

console.log($(this).prev().text());
Comments