1

There are two div sections with the same class and also has same ul and li and a.

I have two jQuery click events in my code. When I click Google both of the jQuery click events fire. But I do not want both to do so, only one. How do I achieve this?

For example, if Google gets clicked I want only that jQuery click event to do something, not the other one. These are the DOM element I am working with:

<div class = "abc">
 <ul>  
  <li class="year_"><a href="www.google.com">google</a></li>
 </ul>
</div>
<div class ="abc">
 <ul>
  <li><a href="www.yahoo.com>yahoo</a></li>
 </ul>
</div>

The href might change so I cannot base my selector on that. The code that I have follows.

$( 'div.abc ul li[class^="year_"]  a' ).click( function(){
    //do something
});

$( 'div.abc ul li a' ).click( function(){
    //do something
});
4
  • 1
    You could just add an unique ID to each link, it'd make reading those selectors much easier IMO. Commented May 11, 2012 at 23:40
  • 3
    Does ul. actually work? That seems to be a bit odd... Commented May 11, 2012 at 23:41
  • 2
    I'm sure jQuery's $.is() or $.not() could come in handy, including maybe even with just one handler... Commented May 11, 2012 at 23:45
  • 1
    ul. is a mistake I removed it from the question. it should have been just ul Commented May 12, 2012 at 1:05

1 Answer 1

5

You could do a conditional statement, finding the li with the "year_" class:

$( 'div.abc ul li a' ).click( function(){
    if ($(this).parents('li').is('[class^="year_"]')){
        //do something
    } else {
        //do something else
    }
});

See jsfiddle.

Sign up to request clarification or add additional context in comments.

3 Comments

This is the appropriate way to tackle the question. +1
I agree (see comment above): jsfiddle.net/EFkUp (And I did see the edit... ;))
The stray ul. period selector should be removed from the example code, as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.