Reputation: 20872
How can I dynamically load the following HTML/JS into the DOM:
<div id="googleDFP" class="googleDFPAD">
<script>googletag.cmd.push(function() {googletag.display('googleDFP');});</script>
</div>
I've no issues appending some HTML to the DOM but I'm unsure how I can also append the script into the DIV.
I want to append this to a DIV called:
<div id="bannerDIV"></div>
The following doesn't work:
$('#bannerDIV').append('<div id="googleDFP" class="googleDFPAD"><script>googletag.cmd.push(function() {googletag.display('googleDFP');});</script></div>');
Note: I need the script to be active once loaded.
thanks for any ideas :)
Upvotes: 0
Views: 163
Reputation: 41143
You could create a (vanilla javascript) function that creates the div
and the script
elements like :
function googleDFP(divTarget) {
var div = document.createElement('div');
div.setAttribute("id", "googleDFP");
div.setAttribute("class", "googleDFPAD");
var myScript = document.createElement('script');
myScript.innerHTML = "googletag.cmd.push(function() {googletag.display('googleDFP');});";
document.getElementById(divTarget).appendChild(div);
document.getElementById("googleDFP").appendChild(myScript);
}
This function accepts the target div ID
as argument. Then call that function any time you want to append those elements to any other element passing the ID of the target element like
googleDFP("bannerDIV");
Upvotes: 0
Reputation: 1010
It's because of a syntax error. You should be careful about what quotes you have in append text. Try following:
$('#bannerDIV').append('<div id="googleDFP" class="googleDFPAD"> <script>googletag.cmd.push(function() {googletag.display(\'googleDFP\');});</script></div>');
Upvotes: 1