You can use the jQuery .index()
and .eq()
methods:
var $testCollection = $('.test'),
i = $testCollection.index($yourElement);
var $next = $testCollection.eq(i + 1);
var $prev = $testCollection.eq(i - 1);
Pergunta
Using jQuery, if I have elements with the class test
scattered throughout an HTML page, with no defined structure to indicate where they might be found, and if I have a variable called currentItem
that contains <div class="test">This is a test.</div>
, which is located halfway through the page, then how can I find the NEXT element with the test
class that appears in the DOM?
Solução
You can use the jQuery .index()
and .eq()
methods:
var $testCollection = $('.test'),
i = $testCollection.index($yourElement);
var $next = $testCollection.eq(i + 1);
var $prev = $testCollection.eq(i - 1);
Outras dicas
You have to use .eq()
along with the .index()
to achieve what you want.
Try,
var xElements = $('.test');
var xNextElement = xElements.eq(xElements.index(currentItem) + 1);
If you are searching for a next sibling then, try
var xNextElement = currentItem.nextAll('.test').first();