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


i need retrieve id of list item next list item being clicked. example, consider following list. now, when 'item 1' clicked, need retrieve 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 dynamic. able next list item using following code:

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

but when try it's id using following code, doesn't work.

$nextid = $li.id; 

or

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

i appreciate if can me issue or suggest alternate solution!

you can use next() function:


update #1

check second evant listener. every time click on button, random number 1 6 generated. use number list element index (minus 1, because index 0 based).


upadate #2

updated first function when user clicks last list element, id of first list element alerted, 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>


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -