SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    Forums Designer
    Join Date
    Jun 2004
    Posts
    422
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    List all selectors

    I'm trying to get all background images and colour values used by page. To do that I want to access css data somehow.

    Is it possible to get complete list of css selectors used on current page or access raw css data or something like that?

  2. #2
    Forums Designer
    Join Date
    Jun 2004
    Posts
    422
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Found it: document.styleSheets[].cssRules[]

    One small problem: document.styleSheets[].cssRules[].style.cssText returns css that is valid for current browser. For example, for transitions Mozilla returns only -moz-transition, but not -webkit-transition that was in original css file. Is it possible to get full text, including items that current browser considers invalid?

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The stylesheets won't tell you what styles the page is using, only what is available, and it doesn't include inline styles.

    You can look at each element and get its current or computed styles, including from style sheets, inline and inherited properties.


    Code:
    function getPageColors(){
    	var doc= document.getElementsByTagName('*'),
    	who, css, L= doc.length, A= [], count, temp;
    	for(var i= 0; i<L; i++){
    		who= doc[i];
    		count= 0;
    		if(who.style){
    			temp= [deepCss(who, 'color'),
    			deepCss(who, 'background-color'),
    			deepCss(who, 'background-image')];
    			while(count<3){
    				css= temp[count++];
    				if(css && A.indexOf(css)== -1) A.push(css);
    			}
    		}
    	}
    	return A.join('\n');
    }
    
    
    Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
    	i= i || 0;
    	var L= this.length;
    	while(i< L){
    		if(this[i]=== what) return i;
    		++i;
    	}
    	return -1;
    }
    function deepCss(who, css){
    	var dv= document.defaultView;
    	if(dv && dv.getComputedStyle){
    		dv= dv.getComputedStyle(who, '');
    		return dv.getPropertyValue(css);
    	}
    	else if(who.currentStyle){
    		var rx=  /\-([a-z])/g;
    		if(css=== css.toUpperCase()) css= css.toLowerCase();
    		css= css.replace(rx, function(a, b){
    			return b.toUpperCase();
    		});
    		return who.currentStyle[css] || who.style[css] || '';
    	}
    }
    alert(getPageColors())

  4. #4
    Forums Designer
    Join Date
    Jun 2004
    Posts
    422
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, that's very useful!


Bookmarks

Posting Permissions

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