adamyonk adamyonk - 1 year ago 151
jQuery Question

jQuery: check if element has CSS attribute

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'));

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;
$(this).css('background-color',newBackground); console.log("new background is: "+newBackground);

Answer Source

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;


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)';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download