Search code examples
javascripthtmldombackground-image

Assign variable to url failed (JavaScript DOM)


Why does URL does not accept variable values like this let pic = 'img_tree.png'; document.body.style.backgroundImage = "url(pic)";

but accept "pic" variable value like this. document.body.style.backgroundImage = "url('"+pic+"')";

<!DOCTYPE html>
<html>
<body>

<h1>Hello World!</h1>
<button type="button" onclick="myFunction()">Set background image</button>

<script>
function myFunction() {
	let pic = 'img_tree.png';
   // document.body.style.backgroundImage = "url(pic)"; ERROR
  document.body.style.backgroundImage = "url('"+pic+"')"; // working fine
}
</script>

</body>
</html>


Solution

  • Because when it's inside the quotes, it's just the letters "p", "i", and "c". But when it's outside the quotes, it's an identifier which is used to look up a value.

    document.body.style.backgroundImage = "url(pic)";
    //                                    ^^^^^^^^^^−−−−−− string, the letters inside
    //                                                     have no special meaning to
    //                                                     JavaScript
    

    vs.

    //                                              vvv−−−−−−−−−−− identifier
    document.body.style.backgroundImage = "url('" + pic + "')";
    //                                    ^^^^^^^         ^^^^−−−− strings