Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: check if element has CSS attribute

Tags:

jquery

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); }; 
like image 498
adamyonk Avatar asked Feb 10 '10 19:02

adamyonk


People also ask

How do you check if an element has a CSS?

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.

How can check CSS property value in jQuery?

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

What is the use of CSS () method in jQuery?

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.


2 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'); }; 
like image 163
David Hedlund Avatar answered Sep 18 '22 19:09

David Hedlund


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 
like image 33
Rabbott Avatar answered Sep 21 '22 19:09

Rabbott