0

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.

6 Answers 6

2

jQuery selectors are not magic; they're just ordinary strings.
You don't need to escape anything.

Instead, you just need ordinary string concatenation.

Sign up to request clarification or add additional context in comments.

Comments

1

You can do it with string concatenation like:

$('.people div[data-face="' + dataNum + '"] i').css('background-image', 'url('+URL+')');

Comments

0

Try

$('.people div[data-face="'+dataNum+'"] i').css('background-image', 'url(\''+URL+'\')');

Comments

0

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);

Comments

0
$('.people div[data-face="' + dataNum + "'"] i').css('background-image', 'url(' + URL + ')');

Comments

0

You do not really need escaping, following code should work:

$('.people div[data-face="'+dataNum+'"] i').css('background-image', 'url('+URL+')');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.