I'm trying to use .index() function of jQuery and I can figure out how it works. Results are not what I expect them to me. Here is a little exemple of why I don't get it :
Html :
<div id="gallery">
<div class="gallery-item">item 1</div>
<div class="gallery-item active">item 2</div>
<div class="clearfix visible-lg"></div>
<div class="gallery-item">item 3</div>
<div class="gallery-item">item 4</div>
</div>
<div id="buttons">
<button id="next">next</button>
</div>
<span id="console">
</span>
JS :
jQuery( document ).ready(function( $ ) {
$("#buttons > #next").click(function (){
var items = $(".gallery-item");
var index = items.find(".active").index();
$("#console").append("index : " + index + "<br />");
var indexWithSelector = items.index(".active");
$("#console").append("index with selector : " + indexWithSelector + "<br />");
var prevAll = items.prevAll(".gallery-item").size();
$("#console").append("prevall : " + prevAll + "<br />");
$.each(items, function(index, val) {
$("#console").append("<br />" + val.className);
});
});
});
I expect all results to be the same : 1 as the active element is the second in a zero-based list. But I get this :
index : -1
index with selector : -1
prevall : 3
gallery-item
gallery-item active
gallery-item
gallery-item
Why? Am I doing something wrong?
Here it is on CodePen : http://codepen.io/anon/pen/meiBA
Update :
I tried to find the active element directly and use index to find it's position and it worked. I tried this :
var active = $(".gallery-item.active");
var index = items.index(active);
//index == 1