Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get next or previous attribute id in jQuery?

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

like image 910
Steffi Avatar asked Mar 22 '11 19:03

Steffi


People also ask

How can I find previous siblings in jQuery?

jQuery prev() Method The prev() method returns the previous sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse backwards along the previous sibling of DOM elements.

How can get ul id in jQuery?

You can use $('li'). parent(). attr('id') to get the id of the parent element.

What is next jQuery?

next() The next() is an inbuilt function in jQuery which is used to return the next sibling of the selected element. Siblings are those having same parent element in DOM Tree.


2 Answers

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/

like image 113
Hussein Avatar answered Oct 29 '22 23:10

Hussein


You can use jQuery's next function to get the next sibling, and prev to get the previous sibling.

like image 34
Greg Avatar answered Oct 29 '22 23:10

Greg