Mithc Mithc - 1 year ago 67
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.

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download