lys916 lys916 - 5 months ago 8
Javascript Question

jquery unable to use find method using a variable

I've been trying to figure out why find method selector is not detecting the 'city' variable. Here's the code.

html

<div id="cities">
<div class="Denver"></div>
<div class="Seattle"></div>
</div>


Jquery - The data I get returned from getCity.php is a string "Denver, Seattle".

$.post("getCity.php", function(data){
var cityArr= data.split(",");
$.each(cityArr, function(i, city){
$('#cities').find('.'+city).html(city);
});

});


This piece of code does not work. Now if i change
find('.'+city)
to
find('.Denver')
or
find('.Seattle')
then it works.. what am i doing wrong?

Answer

I think there is whitespace after , in your string so use trim() or $.trim()

$('#cities').find('.' + city.trim()).html(city);

or

$('#cities').find('.' + $.trim(city)).html(city);
Comments