Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a div after n number of elements using jQuery

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?

like image 534
Steve Avatar asked Feb 03 '26 07:02

Steve


1 Answers

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/

like image 136
kkemple Avatar answered Feb 04 '26 22:02

kkemple



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!