7

Why is it that using variable within :contains() doesn't work? Is there any way to make it work? filter('contains()') didn't work either.

<h2>Test</h2>
<div>Test</div>

var model = $('h2').text();
//variable doesn't work
$('div:contains(model)').css('background','yellow');
//obviously, string works
$('div:contains("Test")').css('background','yellow');
2
  • 2
    Duplicated: See answer here: stackoverflow.com/questions/2191419/… Commented Mar 20, 2013 at 19:20
  • Has nothing to do with text nodes, JS doesn't parse variables inside strings (looks like you may be used to PHP?) You'll have to use $('div:contains('+$modele+')').css('background','yellow'); Commented Mar 20, 2013 at 19:20

5 Answers 5

13

Selectors doesn't use Javascript variables. You have to put the value from the variable in the selector string:

$('div:contains("' + $modele + '")')
Sign up to request clarification or add additional context in comments.

Comments

5

Unlike PHP, Javascript does not support string interpolation.

If you want to use a variable inside a string, you must concatenate it using the + operator.

Comments

5

it just a concatenation issue:

$('div:contains(' + $modele + ')').css('background','yellow');

Comments

1

as stated in @Slaks answer you need to concatenate.

$('div:contains('+$modele+')').css('background','yellow'); works

here is a fiddle to it.

http://jsfiddle.net/CMKsF/

Comments

1

you need to pass it as string .. so concatenate the var with " using + operator.. so that it takes it as string

try this

var $modele = $('h2').text();
//variable doesn't work
$('div:contains("'+$modele+'")').css('background','yellow');

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.