How to identify the child element clicked through the event click on the parent element

Asked

Viewed 1,513 times

0

I have the following code:

<div class="tipo-cadastro">
    <div class="box-logista active">Logista</div>
    <div class="box-distribuidor">Distribuidor</div>
</div>

and the following code in javascript/jQuery:

$('.tipo-cadastro').click((e) => {
    $('.tipo-cadastro').find('div').removeClass('active');
    $(e.currentTarget).addClass('active');
});

My problem is that inside my Function e.currentTarget corresponds to the parent element, that is, the element that has the event click.

I know I could use the event click directly on each child element. But I wonder if it is possible through the event click on the parent element to know which child element was clicked?

  • Possible duplicate of http://answall.com/q/138171/129 or http://answall.com/a/131776/129

1 answer

1


You can use the target:

$('.tipo-cadastro').click((e) => {
  console.log(e.target);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tipo-cadastro">
  <div class="box-logista active">Logista</div>
  <div class="box-distribuidor">Distribuidor</div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.