So I'm playing with $(el).css()
, trying to determine if an element has a border. I use .css("border-style", "solid")
to set the border, which works, but actually it sets 4 individual styles:
border-right-style
border-left-style
border-top-style
border-bottom-style
So, checking for a border is a bit cumbersome as you have to do something like:
if ($(el).css("border-right-style") == "solid" && $(el).css("border-left-style") == "solid" && ...) {}
Simply checking for $(el).css("border-style") != ""
doesn't works since border-style
is always equal to "".
Is there a more elegant way to do this?
border-style
is Shorthand and you cant get them together so you have to get them separatly, because As per Jquery CSS documentation
Shorthand CSS properties (e.g. margin, background, border) are not supported.
For example, if you want to retrieve the rendered margin,
use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.
If you want to know if 4 properties are ALL set, then yes you have to check 4 properties. Although I would cache the selector.
$el = $('a');
if ($el.css("border-right-style") == "solid" && $el.css("border-left-style") == "solid" && $el.css("border-top-style") == "solid" && $el.css("border-bottom-style") == "solid")
{
alert('yay');
}
jsFiddle
I don't know if it is possible to do what you are trying. The DOM only provides the styles for the element that were assigned inline or to the element in script. It doesn't show if it inherited a style such as a border from CSS declarations.
You still have to test the properties but this can make it a little more abstract...
function check(sel, prop) {
var i, property, $o = $(sel), directions = ["left", "right", "top", "bottom"];
for (i = 0; i < directions.length; i++) {
property = $o.css(prop + '-' + directions[i] + '-style');
if (property !== 'solid') {
return false;
}
}
return true;
}
It can display the style values from inherited CSS files....
alert($("selector").css("border-bottom-color"));