How to get next or previous attribute id in jQuery?

Steffi picture Steffi · Mar 22, 2011 · Viewed 34.1k times · Source

I have the following code

<a class="getty" id="1" href="/...">One<./a>
<a class="getty" id="2" href="/...">Two<./a> 
<a class="getty" id="3" href="/...">Three<./a>

When I'll click on Left or right, I'll need to get the previous ID.
Example : If I'm on id="2", I need to get id="1" if I click on left.

$(document).keydown(function(e){
    if (e.keyCode == 37) {
       $('.getty').attr("id");
       return false;
    } });
    if (e.keyCode == 33) {
       $('.getty').attr("id");
       return false;
    } 
});

How can I do that ?

Thanks

Answer

Hussein picture Hussein · Mar 22, 2011

To get the previous id when link is clicked.

$('.getty').click(function(e) {
    e.preventDefault();
    var x = $(this).prev().attr('id');
    alert(x);

});

You can do the same for next by using the next() function

Check working example at http://jsfiddle.net/H3hdy/