There is a list with li elements. Each element is located to the left by 5px than the previous one. Made a trivial indication of the offset for each item. But is it possible to somehow bypass this and make a loop so that each element is to the left by 5px than the previous one? I am not familiar with jquery, but out of fantasy I sketched code like this (non-working):

$('.li-class').css("margin-left",function(i,value){ for (i=1, i<li:last-child,i++){ return margin-left(value) -=5px; } }); 

Is it possible to do this using a cycle and by what means?

    2 answers 2

     $('li').each(function(i){ $(this).css({'margin-left': i*(-5)+ 'px'}); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> 

    • the css method has an overload that allows you to do without a direct call to each - Grundy

     $('#x').click(function(){ $("ul li").each(function(i, item){ $(item).css("margin-left", i*5 + "px") }) }) 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>2222222</li> <li>2222222</li><li>2222222</li> <li>2222222</li> <li>2222222</li> <li>2222222</li> <li>2222222</li> <ul> <button id="x">Click me</button>