Reputation: 123
With Javascript, I want to find the element that contains the "swiper-active-switch" attribute among all the possible elements and have it return to me in which span element it is contained.
<span class="swiper-pagination-switch"></span>
<span class="swiper-pagination-switch"></span>
<span class="swiper-pagination-switch"></span>
<span class="swiper-pagination-switch"></span>
<span class="swiper-pagination-switch swiper-visible-switch swiper-active-switch"></span>
<span class="swiper-pagination-switch"></span>`
Here's how I get the count of span, but I'm not sure how to iterate through them, find my desired attribute and then find out which line it occupies in the source code. In the above example, it is the line 5. So I'd want to get the value "5" back, for example.
try:
var counter = $(this).find("span").length; //full number
alert(counter);
var total = 0;
var hhh = $(this).html();
alert(hhh);
$("span").each(function(){
var n = parseInt($(this).text());
if(n > 0){ //check if element is greater than 0
total ++;
}
});
total = total + 2;
var index = $(".swiper-pagination-switch").index()+2;
alert("total:"+total+" current:"+index);
//and now the actual number for an active page.
Upvotes: 1
Views: 228
Reputation: 160833
$('span.swiper-pagination-switch').index($('.swiper-visible-switch'))
will give you the result, which is 4 because it is 0-indexed, if you want 5, just plus 1.
Upvotes: 2
Reputation: 1121
If the loop is necessary to achieve your activity,and it's more similar to your code, you should try this :
var total = $('span').length;
var searchClass="swiper-pagination-switch";
var searchIndex;
//there is an index return by jQuery.each method
$('span').each(function(index){
if($(this).hasClass(searchClass)){
searchIndex = index;
}
});
console.log('total:'+total+' active:'+searchIndex);
Upvotes: 1