Reputation: 499
I have something like this on my page.
<div class="number_1" style="background-color:red"></div>
<div class="number_2" style="background-color:yellow"></div>
<div class="number_3"></div>
<div class="number_4"></div>
<div class="number_5" style="background-color:red"></div>
I cant change HTML code by adding the class for background-color! It must red from style!
I need function like this
for(var i=1; i<=5; i++){
if($('.number_'+i).hasBackgroundColor('red')){
//something
}else{
//somethign else
}
}
.attr('style')==='background-color: red'
dont seem to work
.css('background-color')
also dont seem to work
Upvotes: 0
Views: 132
Reputation: 56509
You can try using .css() method which return in rgb.
for (var i = 1; i <= 5; i++) {
if ($('.number_' + i).css("background-color") == "rgb(255, 0, 0)") {
//something
} else {
//somethign else
}
}
As T.J. Crowder mention, the above code works only in chrome and not in firefox or IEs.
Also try using RGB color parser in JavaScript
Upvotes: 0
Reputation: 11328
$(document).ready(function() {
$.each($('div') , function(index) {
alert($(this).attr('style'));
});
});
And, then add your additional logic/conditions in loop...
something like this...
$(document).ready(function() {
$.each($('div') , function(index) {
style=$(this).attr('style');
if(style=='background-color: red;' || style=='background-color:red') {
alert($(this).attr('class')+' is red!');
}
});
});
Upvotes: 0
Reputation: 17288
.attr('style')==='background-color: red' dont seem to work
One space will give different results:
$('<div style="background-color:red"></div>').attr('style') === 'background-color: red'
false
$('<div style="background-color:red"></div>').attr('style') === 'background-color:red'
true
Upvotes: 0
Reputation: 40639
Try this,
for(var i=1; i<=5; i++){
if($('.number_'+i).css('background-color')=='red'){ // or ==rgb(255,0,0)
//something
}else{
//somethign else
}
}
Upvotes: 0
Reputation: 927
css('background-color') return color in rgb in your case "rgb(255,0,0)".
Upvotes: 1
Reputation: 2442
Here you get the background-color:
var backgroundColor = $('.number_'+i).css('background-color');
It will return something like "rgb(245, 180, 5)". Red color is "rgb(255,0,0)".
If you prefer getting hexa value, for example #ff0000 for red color, use such a function:
function hexc(colorval) {
var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
delete(parts[0]);
for (var i = 1; i <= 3; ++i) {
parts[i] = parseInt(parts[i]).toString(16);
if (parts[i].length == 1) parts[i] = '0' + parts[i];
}
color = '#' + parts.join('');
}
Upvotes: 5