Eric Saldivar Eric Saldivar - 4 months ago 9
jQuery Question

Jquery to change CSS background: Checking to see if div contains text, then action

I am trying to get my CSS background based on weatherType.

if($('#weatherType:contains("cloudy")')) {
$('body').css('background-image', 'url(https://hd.unsplash.com/photo-1430263326118-b75aa0da770b)');
} else if($('#weatherType:contains("clear sky")')) {
$('body').css('background-image', 'url(https://media.giphy.com/media/3o7rc6sa2RvKo8K5EI/giphy.gif)')
};


HTML

<body>
<div class="text-center">
<h1> Show the Local Weather</h1>
<h3>Front End Developer Project</h3>
<ul class="list-unstyled">
<i class="fa fa-home" aria-hidden="true"></i>
<li class="btn btn-default" id="city"></li>

<i class="wi wi-day-cloudy"></i>
<li class="btn btn-default" id="weatherType"></li>
</br>
<i class="wi wi-thermometer"></i>
<li class="btn btn-default" id="fTemp"></li>

<i class="wi wi-strong-wind"></i>
<li class="btn btn-default" id="windSpeed"></li>
</ul>

Answer

In your code the first if condition would be always true since $(...) returns a jQuery object and which is a truthy value so always the first if block gets executed. Use length property instead.

if($('#weatherType:contains("cloudy")').length) {
//--------------------------------------^^^^^^-------
    $('body').css('background-image', 'url(https://hd.unsplash.com/photo-1430263326118-b75aa0da770b)');
} else if($('#weatherType:contains("clear sky")').length) {
//------------------------------------------------^^^^^^-------
    $('body').css('background-image', 'url(https://media.giphy.com/media/3o7rc6sa2RvKo8K5EI/giphy.gif)')

Or you can use jQuery is() method which returns a Boolean value.

if($('#weatherType').is(':contains("cloudy")')) {
//------------------^^^^-------
    $('body').css('background-image', 'url(https://hd.unsplash.com/photo-1430263326118-b75aa0da770b)');
} else if($('#weatherType').is(':contains("clear sky")').length) {
//-------------------------^^^^-------
    $('body').css('background-image', 'url(https://media.giphy.com/media/3o7rc6sa2RvKo8K5EI/giphy.gif)')