tomc tomc - 1 year ago 53
Javascript Question

Setting background image on dynamic element

I'm trying to set a background image on a dynamically created element however it does not seem to be working. It is supposed to take the "img" property of an object that I have put into an array and then use that for the background image url.


var sponsorArray = new Array();

//Sponsor Constructor Function
function Sponsor(name, img, tier, url, description) { = name;
this.img = img;
this.tier = tier;
this.url = url;
this.description = description;

//A counter for the number of sponsors
Sponsor.num = (Sponsor.num || 0) + 1;

//Insert this object into the sponsors array

var sponsor0 = new Sponsor(
'test sponsor',
'blah blah blah'

var initSponsors = function() {
for (var i = 0; i < sponsorArray.length; i++) {

var sponsor_image = $('<li>', {
'class': 'sponsor-logo',
'id': 'sponsor' + i,
'background-image': 'url(\'' + sponsorArray[i].img + '\')'




<ul id="logo-sponsors">

When I inspect the element it appears that it should work? I'm at a loss...

Answer Source

"background-image" is an invalid jQuery method. .css() on the other hand is valid, so

instead of

        'background-image' : 'url(\'' + sponsorArray[i].img + '\')'


        css : {
          backgroundImage: 'url(\'' + sponsorArray[i].img + '\')'