Is there a way to check an elements parents and find the first one that has a CSS background set and then return that background value?
Something like:
var background = $('element').parents().has(css('background'));
UPDATE: This is the code I'm now using:
jQuery.fn.getBg = function(){ var newBackground = this.parents().filter(function() { return $(this).css('background-color').length > 0; }).eq(0).css('background-color'); $(this).css('background-color',newBackground); console.log("new background is: "+newBackground); };
To check if an element's style contains a specific CSS property, use the style object on the element to access the property and check if it's value is set, e.g. if (element. style. backgroundColor) {} . If the element's style does not contain the property, an empty string is returned.
Get a CSS Property Value You can get the computed value of an element's CSS property by simply passing the property name as a parameter to the css() method. Here's the basic syntax: $(selector). css("propertyName");
jQuery css() Method The css() method sets or returns one or more style properties for the selected elements. When used to return properties: This method returns the specified CSS property value of the FIRST matched element.
If it's not set, fetching it will yield an empty string. Hence
var bg = ('element').parents().filter(function() { return $(this).css('background').length > 0; }).eq(0)
EDIT
Some research shows that css('background')
will always yield an empty string, or undefined
, depending on browser. css('background-color')
will correctly return the color of the element at hand; but also different values for each browser, so it is troublesome to test (transparent
in IE, rgba(0,0,0,0)
in firefox/chrome, for instance, both being accurate ways of specifying transparent).
jQuery.fn.getBg = function() { return $(this).parents().filter(function() { // only checking for IE and Firefox/Chrome. add values as cross-browser compatibility is required var color = $(this).css('background-color'); return color != 'transparent' && color != 'rgba(0, 0, 0, 0)'; }).eq(0).css('background-color'); };
I believe the correct way to do this is to check the .length property.
In your case you'd want to loop through all of your elements and check for the first one that meets
.css('background').length != 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With