views:

1108

answers:

5

I am wondering how I can read CSS comments out of a linked stylesheet.

I have this sample CSS loaded via:

<link rel="stylesheet" type="text/css" media="all" href="test.css" />

 

#test1{ border:1px solid #000; }
#test2{ border:1px solid #000; }
#test3{/* sample comment text I'm trying to read */}

I'm testing this in FF3. The following javascript reads the rules but doesn't read the comments in #test3.

window.onload = function(){
    s=document.styleSheets;
    for(i=0;i < s[0].cssRules.length;i++){
     alert(s[0].cssRules[i].cssText);
    }
}
+4  A: 

Comments will almost always be ignored by an interpreter and therefor will not be available.

Adam Peck
+2  A: 

You can't, that's the entire point of comments.

PlacidBox
A: 

You can't read the CSS file JavaScript, just inspect the results in the DOM. One possible way might be to use an embedded stylesheet, where you can query the textual content of the style tag via the DOM interface. You have to parse the content for yourself, of course.

bandi
+3  A: 

You can access the CSS file using an AJAX query and then parse the results yourself looking for comments. The interpreter won't get in the way then.

As long as the CSS is on the same domain as the page, this will work nicely.

Allain Lalonde
+5  A: 

You could retrieve the stylesheet's contents and use regex to parse the comments. This example uses jQuery to get the stylesheet text and a regular expression to find the comments:

jQuery.get("test.css", null, function(data) {
 var comments = data.match(/\/\*.*\*\//g);
 for each (var c in comments) 
  alert(c);
});

You could also find the stylesheet links using selectors.

Cristian Libardo
Does foreach work with the space there?
Allain Lalonde
@allain: I think so. At least it's in the mozzilla docs https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for_each...in
Cristian Libardo
Oh, it's in new to javascript 1.6 and should probably be avoided for now
Cristian Libardo