How to check which element has been clicked with jQuery?

Sometimes, we want to check which element has been clicked with jQuery.

In this article, we’ll look at how to check which element has been clicked with jQuery.

How to check which element has been clicked with jQuery?

To check which element has been clicked with jQuery, we can add a click event listener to the body element.

Then we can check which element is clicked inside the click event handler with the is method.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<p>
  foo
</p>

<div>
  bar
</div>

<section>
  baz
</section>

to add a few elements into the page.

Then we write:

$('body').click((e) => {
  const target = $(e.target);
  if (target.is('p')) {
    console.log('p clicked')
  } else if (target.is('div')) {
    console.log('div clicked')
  } else if (target.is('section')) {
    console.log('section clicked')
  }
});

We select the body element with $.

Then we call click on it with a callback that gets the clicked element with the e.target property.

Then we check for what’s clicked with the is method called with the selector we’re checking for.

Therefore, when we click on different elements, we should see different text logged.

Conclusion

To check which element has been clicked with jQuery, we can add a click event listener to the body element.

Then we can check which element is clicked inside the click event handler with the is method.