Steve
Steve

Reputation: 5166

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?

Upvotes: 3

Views: 4785

Answers (5)

Aslam Khan
Aslam Khan

Reputation: 378

Below Is example, suppose i want to append html after rl-gallery-item it's very easy.

<div class="rl-gallery">
  <div class="rl-gallery-item"> </div>  
  <div class="rl-gallery-item"> </div>
  <div class="rl-gallery-item"> </div>
  <div class="rl-gallery-item"> </div>
  <div class="rl-gallery-item"> </div>
</div>

Here i will give you two example.

Example 1:

jQuery(document).ready(function(){
  $('.rl-gallery .rl-gallery-item').each(function(i) {
  if ( i === 3 ) {
   $(this).append("<p> using loop </p>");
 }
});

Example 2:

 $('.rl-gallery .rl-gallery-item').eq(6).after('<div class="scrolltowahtsctn">
  <a href="#scrollsection"> <p> לחצו לקבלת פרטים נוספים    </p> </a> </div>');
 });

Upvotes: 0

kkemple
kkemple

Reputation: 992

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/

Upvotes: 8

Albert Xing
Albert Xing

Reputation: 5788

Fiddle

Find all the non-blue divs. For every third div in the list, determine whether it has a .blue div right after. If it doesn't, then insert one.

This method doesn't need to remove elements on each iteration - it just uses a few selectors and loops:

$("div:nth-child(3n)").after("<div class='blue'></div>");

// Simulate adding more red squares
$("body").append("<div /><div /><div /><div /><div /><div />");

$("div:not(.blue)").each(function (i, e) {
    if ((i + 1) % 3 == 0 && !$(e).next().is(".blue"))
        $(e).after("<div class='blue'></div>");
});

Upvotes: 2

wrxsti
wrxsti

Reputation: 3504

Fiddle

If I understand correctly, this should help. Its a basic demo letting you click to dynamically add divs.

var divCounter = 1;
$(document).on('click', '.divAdder', function(){
    $('body').append('<div>' + divCounter + '</div>');
    divCounter++;
});

Followed by a short script that places a "Test" div in the position you would like using the nth-child pseudo selector. Change the variable "insertAfter" to the number you need to insert the div after.

var insertAfter = 8;
$(document).on('click', '.testAdder', function(){
    $('div:nth-child(' + (insertAfter) + 'n)').after('<div>TEST</div>');
});

Hope this helps!

Upvotes: 0

rawr
rawr

Reputation: 31

Check out what I made at this JS fiddle. http://jsfiddle.net/TWLAX/

Here is the function I made.

function insertBetween(selector, markup, n){
    n--; // EQ counts at 0 so sub 1
    if($(selector).eq(n).after(markup)){
        return true;
    } else {
        console.error('insertBetween(): an error has occured.');
    }
}

There shouldn't be any problem adding more div's to the document, as long as you aren't making multiple document objects or one time functions.

Upvotes: 1

Related Questions