jQuery: check if element has CSS attribute

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

Leave a Comment