How to select next 'n' consecutive elements on every click using jQuery?
In below example, I want to select the first 4 li elements on first button click, next 4 on 2nd click and next 4 on 3rd Click, upto 'n' numbers.
$(document).ready(function(){
$(".btn").on('click', function(){
$("li:nth-child(-n+4)").addClass("selected");
});
});
.btn{ text-decoration:none; background:blue; color:#fff; padding:5px; border-radius:4px;float:left;}
ul{ list-style:none;float:left;clear:both;}
ul li{ padding:5px;background:#555; color:#fff; float:left; border-radius:2px; margin:2px; }
.selected{ background:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<a class="btn">select next 4 consecutive elements</a>
<ul>
<li> 1st 4</li>
<li> 1st 4</li>
<li> 1st 4</li>
<li> 1st 4</li>
<li> 2nd 4</li>
<li> 2nd 4</li>
<li> 2nd 4</li>
<li> 2nd 4</li>
<li> 3rd 4</li>
<li> 3rd 4</li>
<li> 3rd 4</li>
<li> 3rd 4</li>
</ul>
You can create a variable initialized to
0
and increment the variable by4
, use.slice()
to select n elements