A
A
Alexey Chertok2015-11-05 12:02:40
css
Alexey Chertok, 2015-11-05 12:02:40

How to append an element between blocks in jQuery?

Good afternoon. Please help us to append a block with ads between news blocks.

I need to add two blocks with ads between the 3rd and 6th news when loading the page.
The news markup is:

<div class="newsBlocks">
    <div class="newsItem"></div>    
    <div class="newsItem"></div>
    <div class="newsItem"></div>
    <div class="newsItem"></div>
    <div class="newsItem"></div>
    <div class="newsItem"></div>
    <div class="newsItem"></div>
    <div class="newsItem"></div>
    <div class="newsItem"></div>
    <div class="newsItem"></div>
</div>


As far as I understand, initially you need to calculate how many news there are in a cycle and only then insert a block with advertising after a certain number, but alas, I don’t know how to do this ;(

Help please.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir, 2015-11-05
@BarnyBroken

In short, here is an example jsfiddle.net/4j44vg01
We take all the blocks, find the one we need, for example, using the eq () method that takes the element number (the countdown starts from zero, so if we want 3 elements, we set 2), the method returns the desired element, and as said Dmitry, use the after or before methods - they insert HTML immediately after and before the current element

D
Dmitry, 2015-11-05
@thewind

Jquery after or before
Desired item $(".newsItem").eq(N)

M
Maxim Nepritimov, 2015-11-06
@nepritimov_m

In the blocks after/before/in which you want to add advertising, you can prescribe a specific class and move on from this. Well, or do this:

var wrapBlocks = $('.newsBlocks'),
    elemBlock = wrapBlocks.find('.newsItem'),
    count = 0,
    advBlock = '<div class="you-adv">Моя реклама </div>';

elemBlock.each(function () {
    if (count === 3 || count === 6) {
        $(this).after(advBlock);
    }
    ++count;
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question