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
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.
You can use $('li'). parent(). attr('id') to get the id of the parent element.
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.
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
You can use jQuery's next function to get the next sibling, and prev to get the previous sibling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With