Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

javascript - Find the next element that comes later in DOM

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...