steve Kim steve Kim - 2 months ago 13
jQuery Question

jQuery target previous divs with integer number

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

Answer

You can grab all of them using prevAll and then take only the first five of those previous elements by using slice.

var num = 5;
$(".start").prevAll().slice(0, num).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>