I'm ready to pass a script to a site where in the content, between 3 and 4, an advertisement will appear.
Can I read the 3rd paragraph of a text and insert a DIV after it, with JS or JQUERY?
I'm ready to pass a script to a site where in the content, between 3 and 4, an advertisement will appear.
Can I read the 3rd paragraph of a text and insert a DIV after it, with JS or JQUERY?
You can get the paragraph using .eq(índice)
and insert something after it using .after()
.
If the container is a div
any, catching id
:
$(function(){
var pub = '<div class="pub">publicidade</div>';
$("#div p:eq(2)").after(pub);
});
// eq(0) = 1º elemento
// eq(1) = 2º elemento
// eq(2) = 3º elemento ←
// eq(3) = 4º elemento
p{
background: yellow;
}
.pub{
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="div">
<p>parágrafo 1</p>
<p>parágrafo 2</p>
<p>parágrafo 3</p>
<p>parágrafo 4</p>
</div>
If the container is itself body
:
$(function(){
var pub = '<div class="pub">publicidade</div>';
$("p:eq(2)").after(pub);
});
// eq(0) = 1º elemento
// eq(1) = 2º elemento
// eq(2) = 3º elemento ←
// eq(3) = 4º elemento
p{
background: yellow;
}
.pub{
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><p>parágrafo1</p><p>parágrafo2</p><p>parágrafo3</p><p>parágrafo4</p>
:eq()
.after()
If I understand correctly, taking into account that your paragraphs are inside a container with an identifier, do with Jquery
as follows:
var div = $('<div> Essa é a DIV de propaganda! </div>');
$('.main').find('p:nth-child(3)').after(div);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><sectionclass="main">
<p> 1º Parágrafo! </p>
<p> 2º Parágrafo! </p>
<p> 3º Parágrafo! </p>
<p> 4º Parágrafo! </p>
</section>
Just locate the third paragraph and after that, use the after()
function to insert your div.
You can get the paragraph using :eq(índice)
and insert something after using .after()
.
$( "body" ).find( "div" ).eq( 2 ).addClass( "aliceblue" );
$(function(){
var container = '<div>publicidade</div>';
$("p:eq(2)").after(container);
});
$( "div" ).eq(1).css( "background-color", "yellow" );
$( "div:eq(0)" ).css( "color", "red" );
div {
margin: 10px;
float: left;
border: 2px solid blue;
}
.aliceblue {
background:aliceblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div>zero</div><div>um</div><div>dois<p>parágrafo1</p><p>parágrafo2</p><p>parágrafo3</p><p>parágrafo4</p></div><div>tres</div><div>quatro</div>
Noticethat
.eq
and:eq
dobasicallythesamething.ThedifferencebetweenthemcanbeseeninthispostbyclickingtheRuntests
buttononthispage eq vs eq ()