0

I have some HTML markup, similar to:

<div id="parentElement">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
</div>

I am attaching an event handler to each child element with jQuery:

$( "div.child" ).on( "click", someFunction );

Is there an easy way for me to figure out which child element was triggered/clicked from the event object? For example, I'd like to be able to determine if the user clicked on the 3rd child <div> versus one of the other child <div>.

4 Answers4

1

You can use currentTarget property of the event object or use jQuery's index() function.

$( "div.child" ).on( "click", function(event){
   console.log(event.currentTarget);
} );

$("div.child").on("click", function(e) {
  console.log(e.currentTarget);
  console.log($(this).index());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parentElement">
  <div class="child">First</div>
  <div class="child">Second</div>
  <div class="child">Third</div>
  <div class="child">Fourth</div>
</div>
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
1

Use index() method to get index based on its siblings and inside the handler this refers to the dom object of clicked element.

$("div.child").on("click", function() {
  console.log($(this).index())
});

$("div.child").on("click", function() {
  console.log('Clicked div' + ($(this).index() + 1))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parentElement">
  <div class="child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
  <div class="child">4</div>
</div>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

Use the jQuery .index() function on the clicked element.

$( "div.child" ).on( "click", function(e){
  alert($(this).index());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parentElement">
    <div class="child">Test1</div>
    <div class="child">Test2</div>
    <div class="child">Test3</div>
    <div class="child">Test4</div>
</div>
Wowsk
  • 3,637
  • 2
  • 18
  • 29
0

You can use jquery index to find the index of child

$( "div.child" ).on( "click", function(event){
console.log($(this).index())

} );

JSFIDDLE

brk
  • 48,835
  • 10
  • 56
  • 78