4

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);
    }
}
3
  • Not sure why that code wouldn't show up in the post properly - just indent every code line 4 spaces! Commented Dec 30, 2008 at 22:09
  • Or select it an press the 10101 button (will add 4 spaces in front of every selected row) Commented Dec 30, 2008 at 22:12
  • Its my first time posting. Still trying to figure it all out =) Commented Dec 30, 2008 at 22:51

5 Answers 5

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@allain: I think so. At least it's in the mozzilla docs developer.mozilla.org/en/Core_JavaScript_1.5_Reference/…
Oh, it's in new to javascript 1.6 and should probably be avoided for now
4

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

Comments

4

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.

Comments

2

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

1 Comment

You can, just see @Cristian Libardo's answer.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.