Answer the question
In order to leave comments, you need to log in
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>
Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question