www.webdeveloper.com
Results 1 to 3 of 3

Thread: Count instances of class use on a page?

  1. #1
    Join Date
    May 2009
    Location
    Rochester, NY
    Posts
    364

    Count instances of class use on a page?

    I'd like to use JavaScript to count how many times I use a CSS class in a document and then tally them in an array, and then display it on a page. What I'd like to do, specifically, is count the instances in the particular page on which I'm running the script. Is there a way to do this? Any help would be appreciated! Thanks!

  2. #2
    Join Date
    Mar 2009
    Posts
    492
    I haven't tested this at all but you might want to give it a shot. Run this function after the DOM has loaded. It should return an object with all the keys being the names of the CSS classes in the page and their respective values will be the number of times they are used in the page. No warranties apply.

    Code:
    function classFinder(){
        var i, len, j, jLen, all, el, cl;
        all = {};
        el = document.getElementsByTagName("*");
        len = el.length;
        for(i = 0; i < len; i++){
    	cl = el[i][className];  //get className of each element
    	if(cl === undefined || cl.length === 0){
    	    continue;
    	}
    	cl = cl.split(' ');  //break down into individual classes
    	jLen = cl.length;
    	for(j = 0; j < jLen; j++){
    	    if(!all[cl[j]]){  //create entry of class name if not already there
    		all[cl[j]] = 0;
    	    }
    	    all[cl[j]]++;  //increment number of specific class found
    	}
        }
        return all;
    }

  3. #3
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,377
    May already be available in the more recent browsers,

    but you can also use: http://www.javascriptsource.com/snip...tsbyclass.html
    or: http://www.dustindiaz.com/getelementsbyclass/
    or: http://snipplr.com/view/37097/getelementsbyclass/

    Or if you already know the class name you want to count,
    see: https://developer.mozilla.org/en-US/...ntsByClassName

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles