Search code examples
jqueryfor-loopjquery-selectorssiblingsnextsibling

Can I make a repeated jQuery next() by for loop?


I wanna select some sibling elements. So I used jQuery .next() but I don't know how to repeat.

// Repeat 3 times
$('#after').next().addClass('selected');
$('#after').next().next().addClass('selected');
$('#after').next().next().next().addClass('selected');
.selected {
	color: red;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li id="after" data-num="3">3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>		
</ul>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How can I make a repeated jQuery next() as specified value by for loop, like this? (of course this is not working.)

$('#after')
  for(var i=0; i<$('#after').data('num'); i+=1){
    .next().addClass('selected')
  }
;

Solution

  • Instead of next() use nextAll()

    $('#after').nextAll("li").addClass('selected');
    

    You do not need to iterate over all the elements. nextAll() will select all the sibling elements down to the source element in the DOM tree.

    If you want to do with out looping statements, then you have to do it like,

    var srcElem = $("#after");
    var srcIndex = srcElem.index() + 1; 
    var index = +srcElem.data("num");
    secElem.closest("ul")
             .find("li:gt("+ (index-1) +"):lt("+ (srcIndex + index) +")")
               .addClass('selected');    
    

    Using loop will be the best approach here, but use it in an optimized way,

     var src = $('#after');
     for (var i = 0, len = +src.data('num'); i < len; i++) {
       src = src.next("li").addClass('selected');
       if (!src.length) { break; }
     }
    

    DEMO