user2613041 user2613041 - 1 year ago 68
CSS Question

Use of quotation marks

Why does this line of code produce the desired results:

document.getElementById('ID').style.backgroundImage = 'url('+ variable +')';

While this line does not:

document.getElementById('ID').style.backgroundImage = "url('+ variable +')";

How do I use quotes in

Answer Source

In Javascript the single and double quote marks are interchangeable but must be using in matching pairs. If your text already contains one style, you can use the other style to preserve the one you want to use as part of the text. So suppose variable = "mypage" then

'url('+ variable +')'

will encode a string as



"url('+ variable +')"

will encode this literally, operators, variable name and all

url('+ variable +')

An example of where you might want to do this is

myname = "John";
sentence = 'My name is "' + myname + '".';

which will give

My name is "John".