How to insert a div.test after every n number of divs and checks whether the div.test already exist in the desired/target position to prevent inserting a duplicate?
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
using something like $.InsertEveryNItems('div.container', '<div class="added"></div>', 3); to end up with this:
<div>1</div>
<div>2</div>
<div>3</div>
<div class="test"></div
<div>4</div>
<div>5</div>
I tried div:eq(3) and div:nth-child(3n), but neither works when new divs are dynamically added to the page.
http://jsfiddle.net/Yg22b/7/ by @KevinB works great, but it removes the div.test element from DOM and re-inserts it on every dynamic addition of more divs. It would be nice if there is a way to avoid that?
Here is a function that will add the desired html after the specified code and it will also track your previous index calls and not allow you to update the same nth selector
var addNth = (function () {
var len, i = 0, className, prevIndexes = [];
function isNew (el) {
return el.hasClass(className); // removed unnecessary parenthesis
}
return function (selector, html, nth, className ) {
var els = $( selector );
className = className || 'test';
if ( $.inArray(nth, prevIndexes) === -1 ) {
prevIndexes.push(nth);
$.each(els, function( index, el ) {
el = $(el);
if ( (i % nth) === 0 && i !== 0 ) {
if ( ! isNew(el) ) {
el.before( html );
}
}
i++;
});
i = 0;
}
}
})();
addNth('div','<p class="test">Test</p>',3);
addNth('div','<p class="test">Test</p>',3); // won't add content
Fiddle here :: http://jsfiddle.net/kkemple/YJ3Qn/3/
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