August 16, 2012

if element hasClass then change background file

Question by gidzior

hi i need to write if statement which checking if span has class “nie” and if so it should changed background file but my statement setting every where first bg file “bg-nie.png”, what is wrong ?

jQuery code

if ($(".rzuty span.mieszkanie").hasClass("nie")) {
        $(".rzuty span.mieszkanie").css("background", "url(img/rzuty/mieszkania/bg-nie.png) repeat");
    } else {
        $(".rzuty span.mieszkanie").css("background", "url(img/rzuty/mieszkania/bg-tak.png) repeat");
    }

HTML

<div id="rzuty07p" class="rzuty">
    <span id="c_07_226" class="mieszkanie" title=""></span>
    <span id="c_07_228" class="mieszkanie" title=""></span>
    <span id="c_07_227a" class="mieszkanie" title=""></span>
    <span id="c_07_227b" class="mieszkanie" title=""></span>
    <span id="c_07_229" class="mieszkanie nie" title=""></span>
    <span id="c_07_005" class="mieszkanie" title=""></span>
    <span id="c_07_006" class="mieszkanie" title=""></span>
    <span id="c_07_008" class="mieszkanie" title=""></span>
    <span id="c_07_007a" class="mieszkanie nie" title=""></span>
    <span id="c_07_007b" class="mieszkanie nie" title=""></span>
</div>

Answer by Curt

This can be simplified to not require an if statement. Just filter your selection further:

var $rzutyspan = $(".rzuty span.mieszkanie");
$rzutyspan.filter(".nie").css("background", "url(img/rzuty/mieszkania/bg-nie.png) repeat");
$rzutyspan.not(".nie").css("background", "url(img/rzuty/mieszkania/bg-tak.png) repeat");

See Demo: http://jsfiddle.net/4A4W7/


Alternatively, this can be achieved with plain CSS:

.rzuty span.mieszkanie
{
   background: url(img/rzuty/mieszkania/bg-tak.png) repeat;
}
.rzuty span.mieszkanie.nie
{
   background: url(img/rzuty/mieszkania/bg-nie.png) repeat;
}

Answer by Starx

Well, you are using a common class .mieszkanie to check and manipulate all the set that matches. Check and manipulate separately:

$(".rzuty span.mieszkanie").each(function(k,v) {
    if ($(this).hasClass("nie")) {
        $(this).css("background", "url(img/rzuty/mieszkania/bg-nie.png) repeat");
    } else {
        $(this).css("background", "url(img/rzuty/mieszkania/bg-tak.png) repeat");
    }
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!