Count selectors in css

Count number of selectors in a css file

is there an existing plugin/app/program/script/whatever that analyzes and counts the css selectors of a file? i want to check if the reason my css file is not working in IE is because my selector count is over 4095 (which im pretty sure is not)

p.s. plus points if there’s a haml/sass/compass solution

corroded

People also ask

We can divide CSS selectors into five categories: Simple selectors (select elements based on name, id, class) Combinator selectors (select elements based on a specific relationship between them) Pseudo-class selectors (select elements based on a certain state)

A CSS selector can contain more than one simple selector. Between the simple selectors, we can include a combinator.

2 Answers

The following snippet can be run in the Firebug console in Firefox to count the total number of CSS selectors (not just CSS rules) and check whether it reaches the limit of 4095 selectors per stylesheet:

var styleSheets = document.styleSheets, totalStyleSheets = styleSheets.length; for (var j = 0; j < totalStyleSheets; j++)< var styleSheet = styleSheets[j], rules = styleSheet.cssRules, totalRulesInStylesheet = rules.length, totalSelectorsInStylesheet = 0; for (var i = 0; i < totalRulesInStylesheet; i++) < if (rules[i].selectorText)< totalSelectorsInStylesheet += rules[i].selectorText.split(',').length; >> console.log("Stylesheet: "+styleSheet.href); console.log("Total rules: "+totalRulesInStylesheet); console.log("Total selectors: "+totalSelectorsInStylesheet); > 

jetli13

My project, Bless CSS, could be what you’re looking for. It will analyze files and split them at the optimum point based on the selector limit.

Читайте также:  Get city by coordinates python

It’s also built in to CodeKit.

Paul Young Avatar

answered Oct 03 ’22 00:10

Источник

Count Number of Selectors in a CSS File

The following snippet can be run in the Firebug console in Firefox to count the total number of CSS selectors (not just CSS rules) and check whether it reaches the limit of 4095 selectors per stylesheet:

var 
styleSheets = document.styleSheets,
totalStyleSheets = styleSheets.length;

for (var j = 0; j < totalStyleSheets; j++)var
styleSheet = styleSheets[j],
rules = styleSheet.cssRules,
totalRulesInStylesheet = rules.length,
totalSelectorsInStylesheet = 0;

for (var i = 0; i < totalRulesInStylesheet; i++) if (rules[i].selectorText) totalSelectorsInStylesheet += rules[i].selectorText.split(',').length;
>
>
console.log("Stylesheet: "+styleSheet.href);
console.log("Total rules: "+totalRulesInStylesheet);
console.log("Total selectors: "+totalSelectorsInStylesheet);
>

How are media queries counted in IE’s CSS selectors limit?

It appears that media queries are not included in the selector limit. All rules within all media queries are counted though.

I wrote a test that performs a binary search to find the turning point where the last selector is ignored. It is available at https://robwu.nl/s/css-selector-limit-test.html. The binary search runs over the range 0 — 4200 and reports how often the input selector fits until the last selector is not applied any more. If the result is greater than 4096, the test case reports «infinity».

Turning point at 4095 for: #DUMMY
Turning point at 4095 for: @media screen(min-width:9px) < #DUMMY >
Turning point at 2047 for: @media screen(min-width:9px) < #DUMMY, #DUMMY >
Turning point at 1023 for: @media screen(min-width:9px) < #DUMMY #DUMMY, #DUMMY, #DUMMY >
Turning point at 1364 for: @media screen(min-width:9px) < #DUMMY > @media screen(max-width:9px) >
Turning point at 1364 for: @media screen(min-width:9px) < #DUMMY > @media screen(max-width:9px) <#DUMMY > @media screen(max-width:9px)< #DUMMY >
Turning point at infinity for: @media screen (min-width:9px) < >
Turning point at infinity for: @media screen (min-width:9px) < >@media screen (min-width:9px) < >@media screen (min-width:9px) < >
Turning point at infinity for: @font-face

The last three tests show that media queries (and other at-rules such as @font-face ) are not counted in the selector limit.

I have seen many «css rule» counter scripts here on Stack Oveflow (e.g. https://stackoverflow.com/a/20496041 and https://stackoverflow.com/a/12313690), but all of them are wrong, unfortunately. A media query appears as one entry in the cssRules/rules list. The right way to count the number of selectors in a stylesheet is to recursively process the style sheet to deal with (nested) @media at-rules.

How can I count the number of elements that match my CSS selector?

As far as I am aware you can’t do this using CSS selectors, but there is a command in Selenium for counting by XPath. The following command will verify there are two disabled buttons:

verifyXpathCount | //td[contains(@class, 'x-hide-offsets')]//button | 2

In Selenium RC (Java) this would look more like

assertEquals(selenium.getXpathCount("//td[contains(@class, 'x-hide-offsets')]//button"), 2);

Count css selectors on a website

Way of Determining How Many Style Rules I have

Through the command-line: You could pass the html file to grep, and do a word count on the occurences of css.

Can CSS detect the number of children an element has?

Clarification:

Because of a previous phrasing in the original question, a few SO citizens have raised concerns that this answer could be misleading. Note that, in CSS3, styles cannot be applied to a parent node based on the number of children it has. However, styles can be applied to the children nodes based on the number of siblings they have.

Original answer:

Incredibly, this is now possible purely in CSS3.

/* one item */
li:first-child:nth-last-child(1) /* -or- li:only-child < */
width: 100%;
>

/* two items */
li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li width: 50%;
>

/* three items */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li width: 33.3333%;
>

/* four items */
li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li width: 25%;
>

The trick is to select the first child when it’s also the nth-from-the-last child. This effectively selects based on the number of siblings.

Credit for this technique goes to André Luís (discovered) & Lea Verou (refined).

Don’t you just love CSS3? /p>

  • http://andr3.net/blog/post/142 (André Luís)
  • http://lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/ (Lea Verou)

CSS get total number of elements

Unfortunately, there is no way in both CSS or LESS to do that. You can go with a JavaScript solution, which is fairly simple to implement.

var allChildren = document.querySelectorAll('#myContainer > *');
var count = allChildren.length;

allChildren[count-1].style.width = 'calc(100% - '+ count * 50 +'px)';

Your specific problem (always better to post a specific problem!) can be solved easily with a HTML table:

table width:300px; 
border:1px solid red;
>

td width:50px;
border: 1px solid blue;
>

td:last-child width:auto;
>

If the data you want to display is not tabular in nature and you just want the layout to look like that, you can use CSS ( display:table , display:table-cell ) to achieve the same result.

#myContainer display:table; 
width:300px;
border:1px solid red;
>

#myContainer > div display:table-cell;
border:1px solid blue;
width:50px;
>

#myContainer > div:last-child width:auto;
>

Checking number of times CSS classes called.

try it

First we need to find our style sheet. In an actual script, this would be written better, but this works on jsFiddle.

var styles = document.head.getElementsByTagName('style');
var css = styles[styles.length - 1].innerHTML;

Then remove comments, and the bodies of each selector (i.e. the stuff between the brackets). This is done because there could be a .com in a background-image property, or any number of other problems. We assume there isn’t a > in a literal string, so that would cause problems.

var clean = css.replace(/\/\*.*?\*\//g, '').replace(/\<[^>]*\>/g, ',');

We can find classes with regular expressions, and then count how many of them occur.

var re_class = /\.(\w+)/g;
var cssClasses = <>, match, c;
while (match = re_class.exec(clean)) c = match[1];
cssClasses[c] = cssClasses[c] + 1 || 1;
>

I used jsprint for displaying our findings. This shows how many times each class is mentioned in our CSS.

jsprint("css classes used", cssClasses);

Thanks to Google and this answer we can find all elements in the body, and loop through them. By default, we assume no classes were used in our HTML, and all classes used were defined.

var elements = document.body.getElementsByTagName("*");
var neverUsed = Object.keys(cssClasses);
var neverDefined = [];
var htmlClasses = <>;

We get each elements class, and split it on the spaces.

for (var i=0; i var e = elements[i]; 
var classes = (e.className || "").split(" ");

This is a three dimensional loop, but it works nicely.

 for (var j=0; j for (var k=0; k

We thought classes[j] was never used, but we found a use of it. Remove it from the array.

 if (neverUsed[k] === classes[j]) neverUsed.splice(k, 1); 
>
>

It looks like we found a class that doesn’t appear in our CSS. We just need to make sure it’s not an empty string, and then push it onto our array.

Also count the number of times each class is used in HTML.

 if (classes[j].length) htmlClasses[classes[j]] = htmlClasses[classes[j]] + 1 || 1; 
>
>
>
jsprint("html class usage", htmlClasses);
jsprint("never used in HTML", neverUsed);
jsprint("never defined in CSS", neverDefined);

How can I use javascript to count the number of items on screen with a certain class?

document.querySelectorAll('#main-div .specific-class').length;

this will look for and find all DOM elements with class specific-class and under(doesn’t matter if it is directly under or not) DOM element with id main-div.

If you want to find all elements with specific multiple classes and get length of elements, you should remove space between classes in querySelectorAll.

So if you have a HTML tag with classes

class="toggle btn btn-default off"
let elements = document.querySelectorAll('toggle.btn.btn-default.off').length;

Источник

Node.js css-selectors-count Count selectors in your CSS file in order to make sure it don’t exceed the limitation of legacy IE browsers.

Count selectors in your CSS file in order to make sure it don’t exceed the limitation of legacy IE browsers.

Usage

var csc = require('css-selectors-count'); var fs = require('fs'); fs.readFile('style.css', 'utf8'>, function(err, file) < if(err) throw err; console.log(csc(file)); // return a object like >);

Scripts

$ npm run test $ npm run coverage

License

The repository of css-selectors-count is in Gitgithub.com/jasonslyvia/legacy-ie-css-lint

Install Command

To install css-selectors-count use the following command:

More Examples

The following examples shows how to use Node.js library css-selectors-count.

var csc = require('css-selectors-count'); var css = ''; process.stdin.setEncoding('utf-8') process.stdin.on('data', function(buf) < css += buf.toString();>); process.stdin.on('end', function() < console.log(JSON.stringify(csc(css))); >); process.stdin.resume();

  • Node.js postcss-bem-linter A PostCSS plugin to lint BEM-style CSS.
  • Node.js immutable-css Best practices suggest avoiding overriding styles from vendor libraries to prevent unwanted side effects.
  • Node.js broccoli-sass-lint This is a pure Node.js scss/sass linter for Broccoli-based applications and plugins.
  • Node.js css-selectors-count Count selectors in your CSS file in order to make sure it don’t exceed the limitation of legacy IE browsers.
  • Node.js stylelint-config-bitcrowd This package provides bitcrowd. s .stylelintrc as an extensible shared config.
  • Node.js broccoli-scss-linter Type: String Default: »
  • Node.js gulp-scss-lint-stylish Stylish reporter for gulp-scss-lint, following the visual style of jshint-stylish.

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

psebborn / countCSSRules.js

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

function countCSSRules ( )
var results = » ,
log = » ;
if ( ! document . styleSheets )
return ;
>
for ( var i = 0 ; i < document . styleSheets . length ; i ++ )
countSheet ( document . styleSheets [ i ] ) ;
>
function countSheet ( sheet )
var count = 0 ;
if ( sheet && sheet . cssRules )
for ( var j = 0 , l = sheet . cssRules . length ; j < l ; j ++ )
if ( ! sheet . cssRules [ j ] . selectorText )
continue ;
>
count += sheet . cssRules [ j ] . selectorText . split ( ‘,’ ) . length ;
>
log += ‘\nFile: ‘ + ( sheet . href ? sheet . href : ‘inline tag’ ) ;
log += ‘\nRules: ‘ + sheet . cssRules . length ;
log += ‘\nSelectors: ‘ + count ;
log += ‘\n—————————‘ ;
if ( count >= 4096 )
results += ‘\n********************************\nWARNING:\n There are ‘ + count + ‘ CSS rules in the stylesheet ‘ + sheet . href + ‘ — IE will ignore the last ‘ + ( count — 4096 ) + ‘ rules!\n’ ;
>
>
>
console . log ( log ) ;
console . log ( results ) ;
> ;
countCSSRules ( ) ;

Источник

Оцените статью