简体   繁体   中英

change the background colour of a div based on the text of another using jQuery and CSS

I would like to change the background colour of a div based on the text of another div using jQuery and CSS.

my HTML looks like this

<div class="livenow-container">                
    <div class="live-content">
    <div class="livenow-artist">Darkpsyde</div>
    <div class="livenow-info">06/05/14 | Transcendent Tuesdays</div>
    <div class="livenow-channelcolour"></div>
    <div class="livenow-channel">Drum and Bass</div>
        <div class="live-thumb"><img src="http://cdn.krisisplay.com/assets/livepic/darkpsydelive.png" class="live"></div>
    </div>
</div>

I would like to change the background-colour of the "livenow-channelcolour" div to a set colour based on the text in the div directly below it called "livenow-channel"

I had someone help me with something similar before and I tried to change the code to achieve this but its not working. The code I am using is the following however happy to use something completely different if it works.

 $(".live-content").each(function() {

    var $el = $(this);
    var color;
    var content = $el.text().toLowerCase();

    if (content.indexOf("drum and bass") !== -1) {
        color = "#39d52d";
    }
    else if (content.indexOf("house") !== -1) {
        color = "#6dc8bf";
    }

    if (color) {
            $el.closest('div')
            .find('.livenow-channelcolour')
            .css("background-colour", color);
        }
}); 

Any help with this simple but frustrating issue is very much appreciated.

Many thanks.

i tried it in fiddle with backgound property of css and its working:

 $el.closest('div')
        .find('.livenow-channelcolour')
        .css("background", color);

Code:

$(".live-content").each(function() {

var $el = $(this);
var color;
var content = $el.text().toLowerCase();

if (content.indexOf("drum and bass") != -1) {
    color = "#39d52d";
}
else if (content.indexOf("house") != -1) {
    color = "#6dc8bf";
}

if (color) {
        console.log("if");
        $el.closest('div')
        .find('.livenow-channelcolour')
        .css("background", color);
    }

}); 

Fiddle DEMO

here is a go at it

http://jsfiddle.net/Icepickle/uJwE6/

$(function() {
    var text = $('.live-content>.livenow-channel').text().toLowerCase(), color;
    switch (text) {
     case 'drum and bass':
        color = '#39d52d';
        break;
     case 'house':
        color = '#6dc8bf';
        break;
     default:
        color = 'transparent';
    }
    $('.live-content>.livenow-channelcolour').css('background', color).text(color);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM