Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery nth-child add html after

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>
like image 894
mtwallet Avatar asked Feb 24 '10 11:02

mtwallet


People also ask

Which jQuery function adds HTML content outside a selection?

prepend() - insert content at the start of selected element (inside its HTML tags) . after() - insert content after the selected element (outside its HTML tags) .

How do I append a div after another div?

To insert element in document after div element using JavaScript, get reference to the div element; call after() method on this div element; and pass the element to insert, as argument to after() method.

What is slice () method in jQuery?

slice() method constructs a new jQuery object containing a subset of the elements specified by the start and, optionally, end argument. The supplied start index identifies the position of one of the elements in the set; if end is omitted, all elements after this one will be included in the result.

What's the difference between the nth of type () and Nth child () selector?

As a general rule, if you want to select an interval of a selector regardless of the type of element it is, use nth-child . However, if you want to select a specific type only and apply an interval selection from there, use nth-of-type .


1 Answers

Using the :nth-child selector (documentation):

$('ul li:nth-child(4n)').after('<li class="clear">This is what I want to add</li>')
like image 142
htanata Avatar answered Oct 04 '22 03:10

htanata