Epik
Epik

Reputation: 3357

I need to find the 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/.

Upvotes: 0

Views: 84

Answers (2)

Matt Ball
Matt Ball

Reputation: 359786

Given that you seem to be unwilling to make assumptions about the structure of the markup, a class-based selector is best. If elements aren't being added/removed then you can select them once and keep them around as an optimization.

var exes = $('.x');
var x1 = $('#x1');
var nextEx = exes.eq(exes.index(x1) + 1);

http://jsfiddle.net/mattball/QKawu

With a truly unpredictable HTML structure, asking for "the next element" only makes sense in the context of "the collection of elements with the specified class name," which is exactly what the above code reflects.

Upvotes: 6

Kolby
Kolby

Reputation: 2865

Find the parent, then get the parent's next sibling, then find the class.

.parent().next().find('.x')

Upvotes: 1

Related Questions