jQuery nth-child add html after

2019-02-06 12:41发布

问题:

I have a simple unordered list with 16 list items. I want to add a new list item after every fourth existing list item using jQuery

How would I do that? Code below:

<ul>
    <li>some stuff</li>
    <li>some stuff</li>
    <li>some stuff</li>
    <li>some stuff</li>

    <li class="clear">This is what I want to add</li>

    <li>some stuff</li>
    <li>some stuff</li>
    <li>some stuff</li>
    <li>some stuff</li>

    <li class="clear">This is what I want to add</li>

    and so on...
</ul>

回答1:

Using the :nth-child selector (documentation):

$('ul li:nth-child(4n)').after('<li class="clear">This is what I want to add</li>')