>>> $$(selector)

January 30th, 2009. Tagged: CSS, firebug, JavaScript

Gotta love the Firebug console, how can anyone not love the Firebug console. It makes testing random pieces of JavaScript a breeze and best of all - you're playing with the live page. Your page or any page for that matter.

Two nice shortcuts you can use in the console are $ and $$.

The first is like document.getElementById() and the second allows you to get elements by using a selector, like w3c's document.querySelectorAll(), now available in the latest browser versions, including IE8.

So go ahead, give $$ a try. For example you can visit yahoo.com, open up the console and try:
>>> $$('.first')
>>> $$('.patabs .first')
>>> $$('#tabs1 li')

Lots of fun!

So here's a little example application I came up with, it spits out unused selectors from your CSS. Just paste it in the multi-line console.

for(var i = 0; i < document.styleSheets.length; i++) {
  for (var j = 0; j < document.styleSheets[i].cssRules.length; j++) {
    s = document.styleSheets[i].cssRules[j].selectorText; 
    if ($$(s).length === 0) console.log(s);

Tell your friends about this post: Facebook, Twitter, Google+

8 Responses

  1. Heh… a cool css trick. I didn’t know that you can access the stylesheets like this.

    It will work on a jQuery powered sites with a little modification:

    if ($(s)[0] === 0) console.log(s);

    And using the jQuery $.each function it can be even shorter:

    $.each( document.styleSheets, function(i, s) {
    $.each( s.cssRules, function (si, ss) {
    if (!$(ss.selectorText)[0]) console.log ( ss.selectorText );

    Neat :-)

  2. Nice, thanks for the comment and the code. jQuery is so cool, eh? Makes everything nicely shorter and less verbose :)

  3. And one geeky prototype version(little slow because of all loops), but for the fun:

    if ($$(s).length === 0) console.log(s);

  4. Yeah, jQuery is my thing :-)

    But when I think about it, this little script can become a nice tool helping to refine the stylesheets of a site.
    Maybe as a greasemonkey script, a bookmarklet or a firebug extension.

    The only problem that I see is that some of the styles can be dynamical (e.i. :hover). And while it’s not hard to identify “:hover” and “:active” selectors – it’s hard (or impossible?) to predict which styles are user-triggered.

    Anyway… just some thoughts at the end of the work week :-)

  5. there is a tool already to find unused styles – called Dust-Me Selectors. A problem I found with it is that it wasn’t counting the in-page <style>s

  6. @Radoslav – whoa, good one! Nothing like a nice all-powerful one-liner :)

  7. You can also install http://firequery.binaryage.com/ to enable jquery on any page.

  8. Thanks a lot for sharing this with all folks you really know what you’re talking about! Bookmarked. Please also discuss with my site =). We will have a link change agreement between us

Leave a Reply