Red Star Red Star - 1 month ago 4
CSS Question

Setting CSS with JavaScript/jQuery forces unwanted double quotes

I want to make a

CSS property have the value

What I do:

<div id="mDiv" style="background-image: url('img2.jpg')" ></div>



OR without jQuery:

document.getElementById("mDiv").style.backgroundImage = "url('img.jpg')";


<div id="mDiv" style="background-image: url("img.jpg")" ></div>

Wanted result:

<div id="mDiv" style="background-image: url('img.jpg')" ></div>

(I also tried making style='...', but it gets converted to double quotes too... What can I do to get the wanted result?)

document.getElementById("mDiv").style.backgroundImage = "url('img.jpg')";

What you need to understand is that the content of your page in the browser is not stored as a string of markup. The page is a hierarchy of objects and properties.

When you execute the above, or the equivalent versions with setAttribute/attr() the other answers are suggesting, the browser is not necessarily storing a string url('img.jpg') anywhere: it's parsing it to extract the url img.jpg, and keeping that. The information about whether you used single quotes, double quotes or no quotes at all to wrap the URL is gone forever.

If you then ask for a serialised form of that as markup, for example by reading the style attribute or grabbing the innerHTML of the document, the browser has to recreate some markup from the properties it has. The browser can choose all sorts of arbitrary ways to serialise that data as long as the output represents the same document content.

There is no reason to expect the output will look much like the markup you put in. In particular, the browser may choose different single or double quote delimiters; it may order attributes differently; it may include different whitespace; and so on.

<div id="mDiv" style="background-image: url("img.jpg")" ></div>

This, however, is not valid HTML, because of the nested quotes. I think you are looking at the element in the DOM Inspector, which in some browsers doesn't necessarily show you an HTML-valid output. If you get the parent element's innerHTML I think you will see the inner quotes escaped to &quot;.