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?
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?
Share Improve this question asked Jan 17, 2012 at 18:32 Tony RTony R 11.5k23 gold badges80 silver badges101 bronze badges 2- why you don't work with classes? – jcvegan Commented Jan 17, 2012 at 18:38
- I usually do but in this particular case, the styles are so dynamic and so specific to each element that it's easier to do it this way. – Tony R Commented Jan 17, 2012 at 18:40
5 Answers
Reset to default 8border-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"));