Skip to content Skip to sidebar Skip to footer

Add Class To Elements With Specific Css Property

I am creating a script that'll iterate each element under 'body' and will check for its 'background-color'. If this background color matches to '#eb2c33', then the script will add

Solution 1:

The problem is that jquery returns rgb(...) even if you declare as HEX so i just added a function to translate hex to rgb:

function hex2rgb(hex) {
  return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}

and than just adapted your code:

$(document).ready(function (e) {

    // Color to change
    var targetHex = hex2rgb('#eb2c33');

    $('body *').each(function(index) {         
        var rgbg = $(this).css('background-color');

        if(rgbg == 'rgb('+targetHex[0]+', '+targetHex[1]+', '+targetHex[2]+')'){
            $(this).addClass('jcbg');
        }

    });
});

Here is the Fiddle


Post a Comment for "Add Class To Elements With Specific Css Property"