[javascript] 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.

This question is related to javascript jquery

The answer is


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

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

And then in your jQuery:

$('.article').click(function(){
    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.


Hope this useful for you.

$(document).click(function(e){
    if ($('#news_gallery').on('clicked')) {
        var article = $('#news-article .news-article');
    }  
});

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:

$('.news-article').click(function(event){    
    var id = event.target.id;
    console.log('id = ' + id); 
});

Another option can be to utilize the tagName property of the e.target. 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:

$('.example-class').click(function(e){
  if ((e.target.tagName.toLowerCase()) == '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");
});

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:

http://api.jquery.com/category/selectors/

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.