jQuery :nth-child() selector

给你一囗甜甜゛ 提交于 2019-12-29 05:29:07

问题


Hi please look at the HTML below. I am trying to use jQuery to get every 3rd instance on the DIVs with class="box" contained within the DIV with class="entry" to have a no right hand margin:

My HTML code:

<div class="entry">

    <div class="box">
        SOME HTML....
    </div><!-- end .box -->

    <div class="box">
        SOME HTML....
    </div><!-- end .box -->

    <div class="box">
        SOME HTML....
    </div><!-- end .box I Want to remove right hand margin on this div -->

    <div class="box">
        SOME HTML....
    </div><!-- end .box -->

    <div class="box">
        SOME HTML....
    </div><!-- end .box -->

    <div class="box">
        SOME HTML....
    </div><!-- end .box I Want to remove right hand margin on this div -->

    <div class="box">
        SOME HTML....
    </div><!-- end .box -->

    <div class="box">
        SOME HTML....
    </div><!-- end .box -->

    <div class="box">
        SOME HTML....
    </div><!-- end .box I Want to remove right hand margin on this div -->

    </div>
    <!--end entry-->

My attempt with jQuery:

   <script>
        $(document).ready(function(){
            $("div.entry:nth-child(3)").css("margin", "0px");
        });
   </script>

I can't get this working can anyone please help? Thanks in advance!


thanks to all who helped the solution provided is indeed correct. I am coding up a supplied template and found that JQuery had been set to run in compatibility mode hence $ was the problem.


回答1:


From the docs (my emphasis)

Matches all elements that are the nth-child of their parent or that are the parent's even or odd children.

You're currently selecting the parent, while you should be selecting children:

$("div.entry > div:nth-child(3)").css("margin", "0px");



回答2:


nth-child also seems to be non-0 indexed. Keep that in mind if you're used to indexing at 0.




回答3:


Your :nth-child selector does not reference n, and you need to reference the inner div in your selector.

Try:

$(document).ready(function(){
  $("div.entry div:nth-child(3n)").css("margin", "0px");
});



回答4:


Try this selector:

div.entry > div.box:nth-child(3n)


来源:https://stackoverflow.com/questions/2026885/jquery-nth-child-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!