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>
prepend() - insert content at the start of selected element (inside its HTML tags) . after() - insert content after the selected element (outside its HTML tags) .
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.
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.
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 .
Using the :nth-child
selector (documentation):
$('ul li:nth-child(4n)').after('<li class="clear">This is what I want to add</li>')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With