最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Applying class to every 3rd list item - Stack Overflow

programmeradmin5浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 4

The 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/

发布评论

评论列表(0)

  1. 暂无评论