I am trying to inject AdSense in the 4th and 7th element of a list item with jQuery but what I have at the moment breaks when I use AdSense but works with ordinary html or text.
Here is what i have
<script>
$(document).ready(function() {
var couter = 1;
$( ".page-itemlist li" ).each(function() {
if(couter==4 || couter==7){
$(this).before( '<li class="adsense-here"> ADSENSE GOES HERE</li>' );
}
couter++;
});
});
</script>
The above works but when I insert AdSense it breaks, this is what I am trying to achieve :
<script>
$(document).ready(function() {
var couter = 1;
$( ".page-itemlist li" ).each(function() {
if(couter==4 || couter==7){
$(this).before( '
<li class="adsense-here">
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7615453880179233"
data-ad-slot="3708363880"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</li>'
);
}
couter++;
});
});
</script>
Multi-line string is not supported by single quote' in javascript.
You need to use backquote `
$(this).before( `
<li class="adsense-here">
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7615453880179233"
data-ad-slot="3708363880"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</li>`
);
$(document).ready(function() {
var couter = 1;
$( ".page-itemlist li" ).each(function() {
if(couter==4 || couter==7){
$(this).before( `
<li class="adsense-here">
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7615453880179233"
data-ad-slot="3708363880"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
<\/script>
</li>`
);
}
couter++;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="page-itemlist">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
</ul>