JonasSH
JonasSH

Reputation: 206

Appending text + variable causes syntax error

When I try to include text, the append(), doesn't work. It causes a syntaxt error (Uncaught SyntaxError: missing ) after argument list).

I don't get why this works:

$(".chatToInfo").append('<div class="green">' + peopleName + '</div>');`

But this doesn't:

$(".chatToInfo").append('<div class="green">'"Sending message to " + peopleName + '</div>');

Upvotes: 0

Views: 67

Answers (4)

Mamun
Mamun

Reputation: 68933

Use ES6's template literals(``) which is much cleaner in this type of situation.

var peopleName = 'John';
var el = `<div class="green">Sending message to ${peopleName}</div>`;
console.log(el);
$(".chatToInfo").append(el);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=".chatToInfo"></div>

Upvotes: 1

Vamsi
Vamsi

Reputation: 684

There is a syntax error. You are closing the opening quotes. That is what is causing the exception.

It should be

$(".chatToInfo").append('<div class="green">"Sending message to "' + peopleName + '</div>')

Upvotes: 1

喝茶的螃蟹
喝茶的螃蟹

Reputation: 144

'<div class="green">'"Sending message to " + peopleName + '</div>'

this is unvalidated string.

the correct string below:

'<div class="green">"Sending message to "' + peopleName + '</div>'

Upvotes: 1

RemyaJ
RemyaJ

Reputation: 5526

Try this,

$(".chatToInfo").append('<div class="green">Sending message to' + peopleName + '</div>');

Upvotes: 1

Related Questions