Toniq
Toniq

Reputation: 5006

jQuery On Event get object listener

I have this markup:

<div class="foo">
   <div class="child"></div>
   <div class="child"></div>
   <div class="child"></div>
</div>

If I want to attach click to all children I will do:

var foo = $('.foo').on('click', ".child", function(e, data){
   //get foo here?
})

When child is clicked how can I get foo here? Disregard the fact that I know here that foo is the parent of clicked child. (not sure closest would work but that would be using selectors again, is there a more direct method?)

Upvotes: 2

Views: 30

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206102

Use jQuery's Event.delegateTarget to refer to the "parent" element, being the Element on whom the event handler was attached (".foo" in your case):

$('.foo').on('click', ".child", function(e, data){
   console.log(e.delegateTarget)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foo">
   <div class="child">1</div>
   <div class="child">2</div>
   <div class="child">3</div>
</div>

To recap, say you click on a <span> which is in a <li> which is in a delegator <ul> element

<ul><li>Lorem <span>ut florem</span></li>

and having:

$("ul").on("click", "li", function(evt) {
  • evt.delegateTarget = <ul>…
  • evt.currentTarget = <li>…
  • evt.target = <span>…

Upvotes: 1

Related Questions