Reputation: 1805
I want to dynamically change the CSS for a specific element. The following hard coded jQuery statement works:
$('.people div[data-face="1"] i').css('background-image', 'url(http://localhost:58888/_pictures/picture_000.jpg)');
However, I need "1" to be a variable ("dataNum") and the actual url needs to be a variable called "URL".
I've been trying various escape characters, but can't get it to work without errors. Here's my latest:
$("\'.people div[data-face=\" " + dataNum + '\"] i\').css(\'background-image\', \'url(' + URL + ')\' ');
What am I missing? Thanks.
Upvotes: 0
Views: 957
Reputation: 1405
You do not really need escaping, following code should work:
$('.people div[data-face="'+dataNum+'"] i').css('background-image', 'url('+URL+')');
Upvotes: 0
Reputation: 13736
You can do it with string concatenation like:
$('.people div[data-face="' + dataNum + '"] i').css('background-image', 'url('+URL+')');
Upvotes: 1
Reputation: 77187
$('.people div[data-face="' + dataNum + "'"] i').css('background-image', 'url(' + URL + ')');
Upvotes: 0
Reputation: 708116
It's just string math (concatenation) for dataNum and a straight substitution for the url variable:
$('.people div[data-face="' + dataNum + '"] i').css('background-image', url);
or if you want to see the string math broken down in more detail:
var selector = '.people div[data-face="';
selector += dataNum;
selector += '"] i';
$(selector).css('background-image', url);
Upvotes: 0
Reputation: 140234
Try
$('.people div[data-face="'+dataNum+'"] i').css('background-image', 'url(\''+URL+'\')');
Upvotes: 0
Reputation: 888213
jQuery selectors are not magic; they're just ordinary strings.
You don't need to escape anything.
Instead, you just need ordinary string concatenation.
Upvotes: 2