Veeza Veeza - 5 months ago 32
HTML Question

Adding content to div with javascript - 'Uncaught SyntaxError: Invalid or unexpected token'?

I get this error from the code below:


Uncaught SyntaxError: Invalid or unexpected token


var d1 = document.getElementById('grid');
d1.insertAdjacentHTML('beforeend', ' <figure>
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/123941/placeimg01.jpg" alt="">
<figcaption>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
</figcaption>
</figure>');


Jsfiddle

Answer

The line breaks in the string are causing the issue. To fix this you could put the string on a single line:

var d1 = document.getElementById('grid');
d1.insertAdjacentHTML('beforeend', '<figure><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/123941/placeimg01.jpg" alt=""><figcaption>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</figcaption></figure>');

Updated fiddle

Or alternatively you can concatenate it on different lines:

var d1 = document.getElementById('grid');
d1.insertAdjacentHTML('beforeend', '<figure>' +
    '<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/123941/placeimg01.jpg" alt="">' +
    '<figcaption>' +
        'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua' +
    '</figcaption>' +
'</figure>');

Example fiddle