jQuery: check if element has CSS attribute

Viewed 73570

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);
};
6 Answers

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
$('selector').parents().filter(function() { return !!$(this).css('background'); });

I'd try something like this:

var background = 0;
$('element').parents().each(function() {
  if (!background && ((e = $(this).css('background')).length > 0)) background = e;
});

Not sure if this exact if-clause works, but the each() should do the trick. The first match will fill the background variable and ignore the rest of the parents while traversing up in the chain.

Edit: Amended to resolve css('background') correctly which may emit an empty string. Additionally, each() does not pass the element, but index and element, thus make use of this instead and discard all parameters.

You could do something like:

$('#test').parents().has(css('background')).filter(':first');

Hope it helps : )

Related