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
238 views
in Technique[技术] by (71.8m points)

javascript - jQuery: Find next element that is not a sibling

Let's say I have following HTML:

<span>
    <span id="x1" class="x">X1</span>
</span>
<span>
    <span>
        <span id="x2" class="x">X2</span>
    </span>
</span>

And $(this) is the <span id="x1" ...>.

What is the best way to find next element matching .x with jQuery?
The structure of the actual document is unpredictable, so the HTML provided is only an example.

I can't use nextAll as it only finds siblings.
If I do $('.x'), it finds all, but I'll have to iterate/compare.
Is there a better solution?

See also: http://jsfiddle.net/JZ9VW/1/.

question from:https://stackoverflow.com/questions/14035206/jquery-find-next-element-that-is-not-a-sibling

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

1 Reply

0 votes
by (71.8m points)

Select all elements with class x, calculate the index of the current element and get the element with the index + 1:

var $x = $('.x');
var $next = $x.eq($x.index(this) + 1);

This works because elements are selected in document order. You only have to select all .x elements once on page load (if they are not dynamically created).


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

...