How to check if a class exists in CSS using jQuery

I have a .hello class in css:

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

How to use jQuery to test .hello class in style or not?
Of course, you need to check the whole style even in the document <link href='style.css' /> .

+10
javascript jquery css
source share
4 answers

Next, it will be checked whether some styles are applied to the element (it does not completely confirm that it came from the stylesheet)

 if ($('.hello').css('color') == '#CCC') { // true } else { // false } 
+1
source share

First, specify the external file in which you want to search in the existing class, then try to replace the spaces with "", if the string "gap" is found to be greater than 0, then the class "gap" is found.

  (function($){ jQuery.get('assets/css/main.css', function(data) { var str = data.replace('n',''); if(str.match(/gap/g).length>0) { console.log('class was found!'); }else{ console.log('no class!'); } }); }) (jQuery); 
+1
source share

You can use getComputedStyle() for an element to get styles.

The color is obtained as rgba and converted to a hex with logic here

 $('.hello').each((i, el) => { if (rgb2hex(getComputedStyle(el).color) == "#cccccc") { console.log('#cccccc el => ', el); } }); function rgb2hex(rgb) { rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); } function hex(x) { let hexDigits = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"); return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16]; } 
 .hello { color: #cccccc; } 
 <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <div class="hello"> hello </div> <div class="hi"> hi </div> 

+1
source share

See the code snippet below, the function returns the found class or identifier from the stylesheet or the style tag that we pass. And returns an empty string if it is 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 this works for you.

0
source share

All Articles