Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying class to every 3rd list item

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>
like image 440
Phill Collins Avatar asked Jan 23 '26 07:01

Phill Collins


2 Answers

The nth-child pseudo-class using 3n can do this.

$( '#contentlist li:nth-child(3n)' ).css({marginRight: '0'});

Demo: http://jsfiddle.net/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:

enter image description here

like image 152
ThinkingStiff Avatar answered Jan 24 '26 21:01

ThinkingStiff


Use the nth-child CSS selector:

$("#contentlist li:nth-child(3n)").css({marginRight: '0'});

Demo (with colors instead of margins): http://jsfiddle.net/ambiguous/DRCLF/

like image 30
mu is too short Avatar answered Jan 24 '26 22:01

mu is too short



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!