Question

I have these divs in my html:

<div class="slide" style=""></div>
<div class="slide" style="background: url(/img/2.jpg)"></div>
<div class="slide" style="background: url(/img/3.jpg)"></div>
<div class="slide" style="background: url(/img/4.jpg)"></div>
<div class="slide" style=""></div>
<div class="slide" style=""></div>
<div class="slide" style=""></div>

I have a var which is an index of one of the divs above, lets say it equals 2, so it's the one with 3.jpg as a background.

Now, I'm trying to get the index of the next div with class "slide", which index is greater than my var and which has no "background" in "style". If there are no divs like that with index greater than my var, I'd like to start searching the divs from the beginning of the list.

Similarly I'm trying to find the last div before my var, with no word "background" in "styles" and similarly, if there is no divs like that, I'd like to start searching from the end of the list.

So basically I'm trying to get a value of 4 for the nextDiv and 0 for the lastDiv, for the example above.

I know that $.nextAll() with :first can help to achieve what I need and I also know, that selecting '.slide' with no "background" in in-line "styles" can be done with $(".slide [style*='background']"), but I can't find a way to put the syntax together adding required conditions.

Please help. Thank you.

Était-ce utile?

La solution

I have a var which is an index of one of the divs above, lets say it equals 2, so it's the one with 3.jpg as a background.

...

Now, I'm trying to get the index of the next div with class "slide", which index is greater than my var and which has no "background" in "style".

What you need for that literal requirement is a combination of eq, nextAll, filter, and (if you really want the index) index.

var index = $(".slide").eq(startingIndex).nextAll(".slide").filter(function() {
    return $(this).attr("style").indexOf("background") === -1;
}).index();

That will give you the element's index relative to its siblings (all of them).

But if you just want the element, use first instead:

var nextSlideWithoutBackground = $(".slide").eq(startingIndex).nextAll(".slide").filter(function() {
    return $(this).attr("style").indexOf("background") === -1;
}).first();

Actually, you could use :gt but it's a pseudo-selector so it may not be any better than using nextAll. Here's what it would look like, though:

var index = $(".slide:gt(" + startingIndex + ")").filter/*...and so on...*/
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top