Home > Back-end >  trying to add background color via javascript to html element
trying to add background color via javascript to html element

Time:06-23

so I have an array, containing titles and covers for movies. I'm trying to display the names in the flexbox, using cover image as background image. I also tried to write it like that: document.div.style.backgroundColor = "url(infoForThatDay[each]['cover'])"; but it didn't work either

Here is the snippet of my code:

for(let each in moviesToDisplay) {
    let div = document.createElement("div")
    div.innerText = moviesToDisplay[each]['title'];
    
    //That is where I'm trying to set the background color
    div.style.backgroundColor = "url(moviesToDisplay[each]['cover'])";
    flex.appendChild(div);
}

Thank you in advance <3 have a great day ^_^

CodePudding user response:

You need to use string interpolation to get the value. You also can't use url values with background-color, you should use background instead:

div.style.background = `url(${moviesToDisplay[each]['cover']})`;

CodePudding user response:

div.style.background = `url("${moviesToDisplay[each]['cover']}")`;

To set image as background, either set backgroundImage or background property.

Also, you will need to use string interpolation else it will set the background image to whatever the string is.

Also, url() takes a string, that's why "" are required.

  • Related