Вопрос

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?

Это было полезно?

Решение

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);

Другие советы

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();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top