I have the following script. At the moment it selects the 3rd item in my list and gives it no margin. The problem is it only does this once, is there a way I can make it happen to every 3rd item in the list? I tried using .each
but I couldn't get it to work successfully.
<script>
$(document).ready(function() {
$("#contentlist li:eq(2)").css({marginRight: '0'});
});
</script>
I have the following script. At the moment it selects the 3rd item in my list and gives it no margin. The problem is it only does this once, is there a way I can make it happen to every 3rd item in the list? I tried using .each
but I couldn't get it to work successfully.
<script>
$(document).ready(function() {
$("#contentlist li:eq(2)").css({marginRight: '0'});
});
</script>
Share
Improve this question
edited Jan 15, 2012 at 23:38
ThinkingStiff
65.4k30 gold badges147 silver badges241 bronze badges
asked Oct 31, 2011 at 5:10
Phill CollinsPhill Collins
1932 silver badges8 bronze badges
0
2 Answers
Reset to default 4The nth-child
pseudo-class using 3n
can do this.
$( '#contentlist li:nth-child(3n)' ).css({marginRight: '0'});
Demo: http://jsfiddle/ThinkingStiff/gjvpR/
HTML:
<ul id="contentlist">
<li>1</li>
<li>2</li>
<li>3</li>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
Script:
$( '#contentlist li:nth-child(3n)' ).css( {marginLeft: '20px'} );
Output:
Use the nth-child
CSS selector:
$("#contentlist li:nth-child(3n)").css({marginRight: '0'});
Demo (with colors instead of margins): http://jsfiddle/ambiguous/DRCLF/