randomstudious
randomstudious

Reputation: 122

How can I get the id of a list item at specific index from a list in JQuery?

I need to retrieve the id of the list item that is next to the list item being clicked. For example, consider the following list. Now, when 'item 1' is clicked, I need to retrieve the id of 'item 2'.

<ul>
<li id="id1">item 1</li>
<li id="id2">item 2</li>
<li id="id3">item 3</li>
</ul>

All these id's are dynamic. I am able to get the next list item using the following code:

$li = $('li').get(ui.item.index() + 1);

But when I try to get it's id by using the following code, it doesn't work.

$nextid = $li.id;

Or

$nextid = $li.attr('id');

I would really appreciate if anybody can help me with this issue or suggest any alternate solution!

Upvotes: 0

Views: 44

Answers (1)

kapantzak
kapantzak

Reputation: 11750

You can use next() function:


UPDATE #1

Check the second evant listener. Every time you click on the button, a random number from 1 to 6 is generated. Use this number to get the list element with this index (minus 1, because index is zero based).


UPADATE #2

Updated the first function so that when user clicks the last list element, the id of the first list element will be alerted, as David Thomas mentioned.

$(document).on('click', 'li', function() {
  var nextID;
  var nextElem = $(this).next(); 
  if (nextElem.length > 0) {
     nextID = nextElem.attr('id');
  } else {
     nextID = $(this).closest('ul').children('li').eq(0).attr('id');
  }     
  alert(nextID);
});

$(document).on('click', '#random', function() {
   var index = Math.floor(Math.random() * 6) + 1;
   var elem = $('ul').find('li').eq(index - 1);
   alert(elem.attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<ul>
<li id="id1">item 1</li>
<li id="id2">item 2</li>
<li id="id3">item 3</li>
<li id="id4">item 4</li>
<li id="id5">item 5</li>
<li id="id6">item 6</li>
</ul>

<button id="random">Get random id</button>

Upvotes: 1

Related Questions