Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery :contains selector using variable

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');
like image 212
veksen Avatar asked Mar 20 '13 19:03

veksen


2 Answers

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

$('div:contains("' + $modele + '")')
like image 141
Guffa Avatar answered Nov 15 '22 22:11

Guffa


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.

like image 39
SLaks Avatar answered Nov 15 '22 22:11

SLaks