32

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 6

47

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');
};
Sign up to request clarification or add additional context in comments.

9 Comments

what exactly is 'x' doing in function(x)? is that a placeholder or is it actually being used for something?
Try this: if ('') alert("The empty string is true!"); -- also you can convert a "truthy" value to boolean with !!.
also, should '.length > 0' be '.length() > 0' ?
@adamyonk: you're right about x. slipped my mind there. the parameter being passed to the filter callback is actually a zero-based index, so that wouldn't have worked at all. as for length, no, it's a property, not a method. length() doesn't work on strings, nor does it on arrays, in javacript. it'd be needed in java, tho.
ok, that makes sense. but now when i try to actually set that background-color value, it's not working, because 'bg' is [object Object] . What do I have to do to be able to set what's returned as a background? Here's my code: jQuery.fn.getBg = function(){ var newBackground = this.parents().filter(function() { return $(this).css('background-color').length > 0; }).eq(0); this.css('background-color',newBackground); };
|
10

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

2 Comments

@David's answer is better, as far as using as boolean rather than length, but had to +1 this to... first answer which will work and needs some rep points.
@Rabbott, i want to get length of elements which has particular css eg. display:flex; how can we do this? Thanks.
5
$('selector').parents().filter(function() { return !!$(this).css('background'); });

2 Comments

An empty string is false in Javascript, you know.
@gaby oh I see what you meant Gaby; never mind! And thanks for the vote!
2

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.

Comments

1

Retrieve element background color or gradient

I came across this as I was trying to apply a background to elements that didn't have one (background gradient or color) already.

This function returns the value of the background gradient or background color if it has one and returns false if it doesn't:

jQuery.fn.getBg = function() {
  var color = $(this).css('background-color');
  var image = $(this).css('background-image');

  if (color != 'transparent' && color != 'rgba(0, 0, 0, 0)') {
    return color;
  }
  if (image != 'none') {
    return image;
  }
  return false;
};

Now if you simply want to test if an element has a background, you can do this using the above function:

var curBack = $(this).getBg();
if (curBack) { /* Element has a background */  }
else { /* Element doesn't have a background */ }

Hopefully this is somewhat resourceful for someone working with gradients.

Comments

-6

You could do something like:

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

Hope it helps : )

2 Comments

css is not a function out of the jQuery context.
Agree with derrick, on top of that the .has() function takes an element selector as a its param.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.