Reputation: 31
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:
div
called test
(.test
)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.
Upvotes: 3
Views: 156
Reputation: 178413
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({});
});
Upvotes: 3
Reputation: 77045
This should be the solution.
if ($("body").hasClass("category")) {
$(".test").before(' <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>');
}
If you want to prevent this when the given class
is present, but there is another class
as well, then change your if
:
if (document.getElementsByTagName("body")[0].class === "category") {
//...
}
Upvotes: 0