-1

The URL is stored in an Array. I want to use it to change the div background image. But it didn't work. e.g.

<div id = "test"></div>
let arr = [1,2,3,'https://reurl.cc/RX3bkD'];
document.getElementById("test").style.backgroundImage = "url(arr[3])";

What could I do? Any help is appreciated.

2 Answers2

0

you are inserting a string into the url instead of the value:

try using the template literal syntax ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals ):

 document.getElementById("test").style.backgroundImage = `url(${arr[3]})`;
sal3jfc
  • 517
  • 4
  • 14
0

You can use quotes to append strings and variables together:

document.getElementById("test").style.backgroundImage = "url(" + arr[3] + ")";

Or you can use a template (note the back ticks are needed) instead of quotes.

document.getElementById("test").style.backgroundImage = `url(${arr[3]})`;
imvain2
  • 15,480
  • 1
  • 16
  • 21