0

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 :)

1
  • 2
    You have quotes that aren't escaped around 'googleDFP'. Commented Mar 8, 2015 at 0:49

2 Answers 2

1

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>');
Sign up to request clarification or add additional context in comments.

Comments

0

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.