Set the background-image values of all divs of a specific class based on ids

I’d like to write a script that automatically sets the background-image url of all the divs on my page with the classes .img-cover based on the value of each ones ‘data-image’ attribute. This way whenever I want to set a background-image I can simply add the correct ‘data-image’ value and class to a div and it will automatically pull the correct image.


CSS doesn’t seem to like having periods in ids, so I removed the ‘.jpg’ from all the IDs and added it to the script, and swapped out a data attribute for the ids. Here’s the html:

<div class="img-cover" data-image="flags_install"></div> 

the new jquery:

$(".img-cover").each(function() {
        var data = $(this).attr('data-image');
        $(this).css("background-image", "url('/img/cover-imgs/" + data + ".jpg');");

I also added console logs and am getting the data values from the first one but it’s just returning “none” for the background-image one still. Any other thoughts?

Because of the naming convention “id=”flags_install.jpg” I think .jpg is parsed as another class applied to the element.

Try approaching it via id=”flags_install” and then
$(this).css(“background-image”, “url(‘/img/cover-imgs/” + id + “.jpg’);”);


$(this).css(‘background-image’, ‘url(/img/cover-imgs/’ + data + ‘.jpg)’);

$(this).css("background-image", "url('/img/cover-imgs/'" + id + ");");
//                                                    ^ there's your problem

That apostrophe is resulting in


Should be

$(this).css("background-image", "url('/img/cover-imgs/" + id + "');");

Incidentally, IDs probably aren’t the best fit for this. Sure it’ll work, but in the spirit with which attributes are intended for certain purposes, a data attribute would be a better fit.