Reputation: 1335
I am trying to check inside my code if a has applied to its css styling the attribute overflow-y: auto. For example if my has a class "abcd", and "abcd" has for its css overflow-y: auto, then the passes. While I've already found a method for jquery, which I am not using, I want to find a method for pure javascript (or Angular JS) to find if the element has a given css attribute. How can I do this without jquery?
Upvotes: 2
Views: 1506
Reputation: 160
You can use the getComputedStyle
method available on the window
object.
var myElement = document.getElementById('myElement');
var overflowValue = getComputedStyle(MyElement).overflowY;
if (overflowValue == 'auto') {
// your code here
}
This method will get values of css properties applied in the moment.
For more info, you can refer here.
hope that helps.
Upvotes: 2
Reputation: 15124
You can check with pure javascript by using this code : document.getElementById('myElement').style['overflow-y']
.
The issue is that this code will works only for inline css style, as in <div style="overflow-y: visible">...</div>
. If the css style comes from a class, you can't find it like this.
The jQuery css
method will find the computed style (so it can detect the real value of overflow-y
even if it comes from a class). But the css
code is very huge. You can find it here : https://github.com/jquery/jquery/blob/master/src/css.js
I want to add that checking if an element has a specific css style is a very bad smell.
Instead of this, you should really consider to check if the element has a specific class. Or if you have using angularjs, a simple boolean in the model will do the trick.
If you really want to check if an element has the overflow-y: auto;
style applied, according to the jQuery code, they use window.getComputedStyle(element)
. They also have a lot of code with a temporary div with a weird position (position:absolute;left:-11111px;width:60px;
) but it is mostly to support old browsers like IE8 and IE9.
In your case, something like this could works : window.getComputedStyle(document.getElementById('myElement'))['overflow-y'] === 'auto'
.
Upvotes: 3