Jquery: contains a selector using a variable

Why is the variable used inside: contains () not working? Is there any way to make it work? filter('contains()')doesn'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');
+5
source share
5 answers

Unlike PHP, Javascript does not support line interpolation.

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

+5
source

Selectors do not use Javascript variables. You must put the value from the variable in the selector line:

$('div:contains("' + $modele + '")')
+11
source

:

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

@Slaks, .

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

.

http://jsfiddle.net/CMKsF/

+1

you need to pass it as a string .. so concaten var with using "the operator +.. so that it treats it as a string

try it

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

All Articles