Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Probably better in javascript, but this can sure include jQuery, or any such library.

I want to find the first .next in the example below.

There are a lot of answers to similar questions that suggest nextAll or siblings... Both are useless here:

$(function(){
  $('.result').text(
    $('.origin').nextAll('.next').text()
      || $('.origin').siblings('.next').text()
      || 'both failed'
  )
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="whatever">
  <p class="result"></p>
  <p class="origin">1</p>
</div>
<p class="next">2</p>
<p class="next">3</p>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
227 views
Welcome To Ask or Share your Answers For Others

1 Answer

Based on the awesome answer by @mrtsherman, I wrote this more complete solution and tested it to work on Chrome and Safari:

$(function() {
  $('.result').text(
    $('.origin').below('.next').text()
  );
});

(function($) {
  $.fn.below = function(sel) {
    var $result = $(sel).first();
    if ($result.length <= 0) {
      return $result;
    }
    $result = [];
    var thisIndex = $('*').index($(this));
    var selIndex = Number.MAX_VALUE; // Number.MAX_SAFE_INTEGER is not yet fully supported
    $(sel).each(function(i, val) {
      var valIndex = $('*').index($(val));
      if (thisIndex < valIndex && valIndex < selIndex) {
        selIndex = valIndex;
        $result = $(val);
      }
    });
    return $result;
  };
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="whatever">
  <p class="result"></p>
  <p class="origin">1</p>
</div>
<p class="next">2</p>
<p class="next">3</p>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...