Reputation: 467
I have a web program that can change stylesheets (don't ask), I need to get the background-color property value for a class using jquery. The class(es) are like below, but each style sheet will have a different colour.
DIV.row.error DIV.field INPUT.input-field
{ background: #fbdad8; border:1px #ef4035 solid; -webkit-border-radius: 0.3em; -moz-border-radius: 0.3em; -o-border-radius: 0.3em; border-radius: 0.3em; }
I have tried using the code before, but it is always white, any ideas?
var checked = $('#<%=chkTermsAgreed.ClientID %>').attr('checked');
var toChange = $('#<%=lblTermsAgreed.ClientID %>')
if (!checked) {
var bgColor = $('<div class=\"row error\"><input class=\"input-field\"/></div>').hide().appendTo("body");
bgColor = bgColor.find('.input-field');
toChange.css('background-color', bgColor.css('background-color'));
bgColor.remove();
}
Upvotes: 0
Views: 258
Reputation: 382150
The only solution I see enabling to get the background-color even if no element of the class is present is reading the stylesheets in js.
The good news is they are browsable objects and it's efficient to read them as they're yet parsed.
You can iterate for example on all rules like this in order to find your background-color :
for (var i=0; i<document.styleSheets.length; i++) {
var styleSheet = document.styleSheets[i];
var cssRules = styleSheet.rules; // chrome, IE
if (!cssRules) cssRules = styleSheet.cssRules; // firefox
for (var j=0; j<cssRules.length; j++) {
var rule = cssRules[j];
console.log(styleSheet.href, rule);
if (rule.selectorText=="DIV.row.error DIV.field INPUT.input-field") {
console.log('found it : ', rule.style.getPropertyValue('background-color'));
}
}
}
}
Upvotes: 2
Reputation: 1
As i understand you're trying to get background-color style of $('div.row.error input[class="input-field"]')
class. This problem solves itself when you clarify what you want to get:
Now let's code. Here is my proposal:
var checked = $('#<%=chkTermsAgreed.ClientID %>').attr('checked');
var toChange = $('#<%=lblTermsAgreed.ClientID %>');
var source = $('div.row.error input[class="input-field"]');
if (!checked) {
toChange.css('background-color', source.css('background-color'));
}
I tried the selector in inspector. It works. Hope this helps. Cheers.
Upvotes: 0