0

QUESTION:

I would like to do something similar to this:

var code = (<ins>...</ins><script>...</script>)

document.getElementById("rightScroll").append(code);

What is the correct syntax ?

EDIT: Of course this syntax is incorrect, that's why I am asking for a solution here.


SITUATION:

The element will be added to rightScroll every time the user scrolls 100vh

Coder1000
  • 4,071
  • 9
  • 35
  • 84

2 Answers2

1

There's a typo on the getElementById method, and the string you are building is not in quotes. I've roughly quoted the string you've provided, but it will likely need extra attention where your ... code is.

var code = "<ins class=\"adsbygoogle\"" +
         "style=\"display:block;width:300px;height:600px;margin-bottom: 20px;\"" +
         "data-ad-client=\"...\"" +
         "data-ad-slot=\"...\"></ins>" +
         "<script>" +
         "(adsbygoogle = window.adsbygoogle || []).push({});" +
         "</script>";

document.getElementById("rightAdScroll").append(code);
//                   ^^ was missing "Id"

This will only work though if you have an append method on your DOM element. append is a jQuery method but it doesn't appear that you are using it directly in this case.

I'd recommend either making 2 calls to:

var myElem = document.getElementById("rightAdScroll");
myElem.appendChild(insTag);
myElem.appendChild(scriptTag);

or use jQuery (if you have it loaded already):

$('#rightAdScroll').append(code)
document.getElementById("rightAdScroll").append(code);
scunliffe
  • 62,582
  • 25
  • 126
  • 161
1

You need to create the elements as dom elements:

var ins = document.createElement("ins");
ins.className = 'adsbygoogle';
ins.style = 'display:block;width:300px;height:600px;margin-bottom: 20px;';
var attClient = document.createAttribute('data-ad-client');
attClient.value = '...';
ins.setAttributeNode(attClient);
var attSlot = document.createAttribute('data-ad-slot');
attSlot.value = '...';
ins.setAttributeNode(attSlot);

var myScript = document.createElement("script");
myScript.setAttribute('type', 'text/javascript');
myScript.innerHTML = '(adsbygoogle = window.adsbygoogle || []).push({});';

var rightScroll = document.getElementById("rightAdScroll");
rightScroll.appendChild(ins);
rightScroll.appendChild(myScript);

Fiddle: https://jsfiddle.net/9tdn2qcd/1/

Martina
  • 739
  • 3
  • 13