Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include Adsense on specific pages

I have an Adsense code snippet like below and I want to include it only on the pages whose body tag has a class of "category" (body class="category") and I want to place it before div called test (.test)

To do that, I was thinking of using:

  if ($("body").hasClass("category")) {

  } 

But, I am a JS newbie and I got stuck with 2 things:

  1. How to show that adsense block (code below) before div called test (.test)
  2. If the page has any other class, I need that adsense code gone from the page.

This is the code for adsense

  <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
  <ins class="adsbygoogle"
       style="display:block"
       data-ad-client="ca-pub-641651684125955"
       data-ad-slot="84616945153"
       data-ad-format="auto"></ins>
  <script>
  (adsbygoogle = window.adsbygoogle || []).push({});
  </script>

I am not a native English speaker but I tried to explain it the best way I could.

like image 459
Gomet G Avatar asked Apr 01 '26 07:04

Gomet G


1 Answers

Try this

  • I am using template literals for the ins code

  • I test that there is only one class, "category" and no other class on the class statement - you could also use classList and count them


if ($("body")[0].className=="category") { 
   $(".test").before(`<ins class="adsbygoogle"
       style="display:block"
       data-ad-client="ca-pub-641651684125955"
       data-ad-slot="84616945153"
       data-ad-format="auto"></ins>`);
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = location.protocol+"//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
    $("head").append(s);
   (adsbygoogle = window.adsbygoogle || []).push({});
});
like image 113
mplungjan Avatar answered Apr 03 '26 19:04

mplungjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!