Check which element has been clicked with jQuery

I am trying to use an 'if' statement to determine which element was clicked.

Basically I am trying to code something along the lines of:

if (the element clicked is '#news_gallery li .over') {
    var article = $('#news-article .news-article');
} else if (the element clicked is '#work_gallery li .over') {
    var article = $('#work-article .work-article');
} else if (the element clicked is '#search-item li') {
    var article = $('#search-item .search-article');

What is the proper jQuery syntax for this? Many thanks in advance.



Use this, I think I can get your idea.

Live demo:

$('body').click(function(e) {

    var target = $(, article;

    if ('#news_gallery li .over')) {
       article = $('#news-article .news-article');
    } else if ('#work_gallery li .over')) {
       article = $('#work-article .work-article');
    } else if ('#search-item li')) {
       article = $('#search-item .search-article');

    if (article) {
       // Do Something

So you are doing this a bit backwards. Typically you'd do something like this:

?<div class='article'>
  Article 1
<div class='article'>
  Article 2
<div class='article'>
  Article 3

And then in your jQuery:

    article = $(this).text(); //$(this) is what you clicked!

When I see things like #search-item .search-article, #search-item .search-article, and #search-item .search-article I sense you are overspecifying your CSS which makes writing concise jQuery very difficult. This should be avoided if at all possible.


Answer from vpiTriumph lays out the details nicely.
Here's a small handy variation for when there are unique element ids for the data set you want to access:

    var id =;
    console.log('id = ' + id); 

The basis of jQuery is the ability to find items in the DOM through selectors, and then checking properties on those selectors. Read up on Selectors here:

However, it would make more sense to create event handlers for the click events for the different functionality that should occur based on what is clicked.


Hope this useful for you.

    if ($('#news_gallery').on('clicked')) {
        var article = $('#news-article .news-article');

Another option can be to utilize the tagName property of the It doesn't apply exactly here, but let's say I have a class of something that's applied to either a DIV or an A tag, and I want to see if that class was clicked, and determine whether it was the DIV or the A that was clicked. I can do something like:

  if (( == 'a') {
    console.log('You clicked an A element.');
  } else { // DIV, we assume in this example
    console.log('You clicked a DIV element.');
$("#news_gallery li .over").click(function() {
    article = $("#news-article .news-article");


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.