tags:

views:

50

answers:

2

The first one below works, that is a:first detects the 1st link, but a:second doesn't. How can I detect the 2nd link on a page using jQuery?

<script type="text/javascript">
    $(document).ready(function() {

        $('a:first').click(function() {
            alert('you clicked 1st link');
        });

        $('a:second').click(function() {
            alert('you clicked 2nd link');
        });

    });
</script>

<a href="#">1st Link</a>
<a href="#">2nd Link</a>
+2  A: 

You use eq(), like so:

$('a').eq(1).click(...);

Or the selector version:

$('a:eq(1)').click(...);

It is 1 because eq is 0-based.

Paolo Bergantino
A: 

You can use :eq(1) like this:

$('a:eq(1)').click(function() {
  alert('you clicked 2nd link');
});

You can test it here. Or .eq(1) like this:

$('a').eq(1).click(function() {
  alert('you clicked 2nd link');
});

Test that version here. Unlike :nth-child(), the eq versions are for the index, which is 0-based.

Nick Craver