jquerydomnextsibling

Find next element out of parent using jQuery


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.


Solution

  • 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>