0

I am trying to create append a script element dynamically on page load. I found a few solutions but the code would only work for a script element with one line. How do I generate this multi-line code using Javascript?

Here's the format:

<script type="text/javascript">
 mmd_srp_listings.push({
 target: '[data-mmd-id="12345"]',
 listedPrice: 19415,
 retailPrice: 19795,
 mileage: 12,
 vehicleStatus: 1,
 vin: "1G1PC7RY2G7100691",
 year: 2016,
 make: "Chevrolet",
 model: "Cruze Limited",
 trim: "LS",
 stock: "106403",
 img: 'http://photos.dealersite.com/vin/1G1PC5SH2G7139692_1.jpg?w=240&404=default',
 vdpLink: "http://www.dealersite.com/new/2016-Chevrolet-Cruze Limited-1G1PC5SH2G7139692"
 });
</script>

..and what I tried so far:

function myFunction() {
    var x = document.createElement("SCRIPT");
    var t = document.createTextNode("mmd_srp_listings.push({
     target: '[data-mmd-id="12345"]',
     listedPrice: 19415,
     retailPrice: 19795,
     mileage: 12,
     vehicleStatus: 1,
     vin: "1G1PC7RY2G7100691",
     year: 2016,
     make: "Chevrolet",
     model: "Cruze Limited",
     trim: "LS",
     stock: "106403",
     img: 'http://photos.dealersite.com/vin/1G1PC5SH2G7139692_1.jpg?w=240&404=default',
     vdpLink: "http://www.dealersite.com/new/2016-Chevrolet-Cruze Limited-1G1PC5SH2G7139692"
     });");
    x.appendChild(t);
    document.body.appendChild(x);
}
Paolo
  • 1
  • 1
  • 1
    I guess the real question is, why does it matter if it's on one or multiple lines? That script will be interpreted the same way in both cases. – Heretic Monkey Feb 23 '16 at 21:20
  • 1
    Check the string you passed to the createTextNode method. I see a couple of double quotation used inside of the string and it may be corrupting the string itself. Try to use single quotations for example in trim: 'LS'. – wilsotobianco Feb 23 '16 at 21:23
  • What kind of errors are you getting? – sm1215 Feb 23 '16 at 21:54

0 Answers0