Use jQuery to check if an 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 frame, which works, but actually it sets 4 separate styles:

 border-right-style border-left-style border-top-style border-bottom-style 

So, checking the border is a little cumbersome, since you need to do something like:

 if ($(el).css("border-right-style") == "solid" && $(el).css("border-left-style") == "solid" && ...) {} 

Just checking for $(el).css("border-style") != "" Does not work, because border-style always equal to "".

Is there a more elegant way to do this?

+6
source share
5 answers

border-style is a shorthand, and you cannot put them together, so you need to separate them, because according to the JQuery CSS Documentation

 Shorthand CSS properties (eg 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. 
+8
source

If you want to know if 4 properties are set to ALL, then yes, you should 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

+3
source

I do not know if you can do what you are trying. The DOM provides only styles for an element that have been assigned to inline or to an element in a script. It does not show if it inherited a style, such as a border from CSS declarations.

+1
source

You still need to check the properties, but this can make it a bit 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; } 
+1
source

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

alerts ($ ("selector") CSS ("bottom border color").);

0
source

Source: https://habr.com/ru/post/906224/


All Articles