Count the number of elements between the elements "this" and "that"

I am trying to understand how a “far” remote element in the DOM relates to a specific other element.

<li>item1</li>
<li>item2</li>
<li class="active">item3</li>
<li>item4</li>
<li>item5</li>
<li>item6</li>
<li>item7</li>

Therefore, when a user clicks on an item, he must return the distance to the active element: So item1: return -2, item4: return 1, item6: return 3etc.

+5
source share
2 answers

I believe you can do this index()method ...

Something like that:

var value = $('li').index() - $('li.active').index();
+6
source

Here you go:

$( ul ).delegate( 'li', 'click', function () {
    var idx1 = $( this ).index(),
        idx2 = $( this ).siblings().andSelf().filter( '.active' ).index();

    var distance = idx1 - idx2;

    // do stuff with distance
});

Live demo: http://jsfiddle.net/aeEBP/

+2
source

All Articles