I have an amount of div elements, i would like to target a specific number of the closet elements, in this case the closest 2 either side of itself and add a class.
$(document).ready(function() {
var dot = $('.dot3');
if (dot.length > 5) {
var activeDot = $('.dot3.active');
var closestDots = $(activeDot).siblings(3);
$(closestDots).css('background-color', '#ff0000');
$(activeDot).css('background-color', '#ff0000');
}
});
.dot3 {
background-color: #000;
height: 10px;
width: 10px;
border-radius: 100%;
display: inline-block;
margin: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dot3">
</div>
<div class="dot3">
</div>
<div class="dot3">
</div>
<div class="dot3 active">
</div>
<div class="dot3">
</div>
<div class="dot3">
</div>
<div class="dot3">
</div>
3
Answers
To get the elements on either side of the target element you could use the
.next()
and.prev()
methods:Since the active dot and its siblings are all getting the same treatment, you could arguably keep things clearer by combining them all into a single collection before altering the CSS:
If you need to support an arbitrary number of previous and next siblings, you can define your own methods called
nextN
andprevN
that take an integer– this is a rudimentary start without any error handling or checking for out of bounds:UPDATE based on Rory’s answer, I have improved the helper methods to take advantage of
nextAll()
andprevAll()
in lieu of looping:You can use the below jquery to add before and after class which is active div.
To do what you require you can use
prevAll()
/nextAll()
to get the preceding/following dot elements, thenslice()
to limit the selection to the 2 nearest in each direction. Then you can apply a CSS class to them to add the required syling.