2

I've the following DOM structure:

<label>
  <span class="tt">
    <a href="#" class="editable">Hello1</a>
    <a href="#" class="editable">Hello2</a>
    <a href="#" class="editable">Hello3</a>
    <a href="#" class="editable">Hello4</a>
  </span>
  <a href="#" class="editable">Hello5</a>
</label>

When I click on the anchor Hello3, I need to get Hello4 and its working absolutely fine. But If I click on the link Hello4, I need to get Hello5 which I'm not getting correctly.

I'm using the following code:

$(document).on('click','.editable',function(){
  console.log($(this).nextAll('.editable').first());
});

What I actually want is to get the next element having class of editable in the label tag when I click on an anchor.

Manish Jangir
  • 5,329
  • 4
  • 42
  • 75

2 Answers2

5

You can't use nextAll() as it is based on sibling elements, in your case all the editable elements are not siblings.

You can use a index based lookup to find the next element like

$(document).on('click', '.editable', function() {
  var $all = $('.editable');
  snippet.log($all.eq($all.index(this) + 1).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<label>
  <span class="tt">
    <a href="#" class="editable">Hello1</a>
    <a href="#" class="editable">Hello2</a>
    <a href="#" class="editable">Hello3</a>
    <a href="#" class="editable">Hello4</a>
  </span>
  <a href="#" class="editable">Hello5</a>
</label>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

You can use the siblings function that returns all siblings of a given element in addition with class selector that select elements of a specific class. Something like this:

$(document).on('click','.editable',function(){
  console.log($('.tt').siblings('.editable').first());
});
JArgente
  • 2,239
  • 1
  • 9
  • 11