Tony R
Tony R

Reputation: 11524

Use JQuery to check if element has a border?

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?

Upvotes: 6

Views: 8054

Answers (5)

V Ranganadh Eduvaka
V Ranganadh Eduvaka

Reputation: 1

It can display the style values from inherited CSS files....

alert($("selector").css("border-bottom-color"));

Upvotes: 0

lsoliveira
lsoliveira

Reputation: 4640

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;
}

Upvotes: 1

pseudosavant
pseudosavant

Reputation: 7244

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.

Upvotes: 1

dku.rajkumar
dku.rajkumar

Reputation: 18578

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.

Upvotes: 8

Sinetheta
Sinetheta

Reputation: 9449

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

Upvotes: 3

Related Questions