Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a class exists in CSS with jQuery

I have class .hello in css:

<style>
    .hello { color:#ccc }
</style>

How can use Jquery to check class .hello exist in style or not?
Of course, it need to check all style even in <link href='style.css' /> document.

like image 425
Hai Tien Avatar asked Jan 11 '16 07:01

Hai Tien


People also ask

How do you check if a div has a class in jQuery?

To check if an element in jQuery has class, follow this syntax: $(selector). hasClass(className); The selector is used to specify the elements to check.

How can check CSS property value in jQuery?

How can check CSS property value in jQuery? Get a CSS Property Value You can get the computed value of an element's CSS property by simply passing the property name as a parameter to the css() method. Here's the basic syntax: $(selector). css(“propertyName”);

How do you know if an element has a specific class?

To check if the element contains a specific class name, we can use the contains method of the classList object.


1 Answers

See below code snippet, the function returns the found class or id from the stylesheet or from style tag we pass. And returns an empty string if not found.

<script type="text/javascript">
function getDefinedCss(s){
    if(!document.styleSheets) return '';
    if(typeof s== 'string') s= RegExp('\\b'+s+'\\b','i'); // IE 
capitalizes html selectors

    var A, S, DS= document.styleSheets, n= DS.length, SA= [];
    while(n){
        S= DS[--n];
        A= (S.rules)? S.rules: S.cssRules;
            for(var i= 0, L= A.length; i<L; i++){
           tem= A[i].selectorText? [A[i].selectorText, 
A[i].style.cssText]: [A[i]+''];
            if(s.test(tem[0])) SA[SA.length]= tem;
        }
    }
    return SA.join('\n\n');
}
       console.log(getDefinedCss ('ui-helper-hidden'));

                  </script>

Let me know if it works for you.

like image 136
Patrick R Avatar answered Oct 31 '22 20:10

Patrick R