jQuery target previous divs with integer number

Tags: jquery
Question!

I have following setup:

<div class="item"></div>
<div class="item"></div>
<div class="item"></div>//Need to target this
<div class="item"></div>//Need to target this
<div class="item"></div>//Need to target this
<div class="item"></div>//Need to target this
<div class="item"></div>//Need to target this
<div class="item start"></div>//starting point
<div class="item"></div>

From start class div, I need to target 5 divs previous to it. So that all previous 5 will get a new class (addClass) like below:

<div class="item"></div>
<div class="item"></div>
<div class="item good"></div>
<div class="item good"></div>
<div class="item good"></div>
<div class="item good"></div>
<div class="item good"></div>
<div class="item start"></div>//starting point
<div class="item"></div>

I have following:

var num = 5; //integer number
$(".start").prevUntil(??).addClass('good'); //??

How would I use the integer number to do this?

To clarify it better, the start class is the starting point and I need to add the class good to 5 previous divs from this starting point.

Thanks

By : steve Kim


Answers

Try this:

$(document).ready(function(){
     
     $(".start").prevAll("div").slice(0,5).addClass("good");
     
 })
.item::after {
  content: "ITEM";
}
.item.start::after {
  content: "START";
}
.item.good::after {
  content: "GOOD";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item start"></div>
<div class="item"></div>

By : ehsan


Instead of using jQuery's prevUntil() function, you may simply use prev() for about the number of times you want to. A quick example would look like this:

var el = $('.start');
for (var i = 0; i < 5; i++) {
  el = el.prev();
  el.addClass('good');
}

https://jsfiddle.net/dzyvxzp3/1/

By : Aer0


I would use the following:

var startIndex = $('.start').index();
var endIndex = startIndex - 5;

for(var i = startIndex - 1; i >= endIndex; i--){
    $('.item').eq(i).addClass('good');
}

Updated to not add class 'good' the start index.

https://jsfiddle.net/n2723fmu/



This video can help you solving your question :)
By: admin