classes vs. IDs

Skip to first unread message

Rick Lowes

unread,
Jan 10, 2012, 9:06:17 AM1/10/12
to Object Oriented CSS
I know with OOCSS classes are preferred rather than IDs for styling,
but IDs are acceptable as Javascript hooks. However, are IDs PREFERRED
for JS hooks? I'm not really very familiar with JS, so not sure if
this is a ridiculous question or not :)

Nathan Graves

unread,
Jan 10, 2012, 9:10:54 AM1/10/12
to object-or...@googlegroups.com
I typically prefer IDs as hooks because it helps to keep my classes clean. Sometimes if a class is expressly used as a JS hook, then one might forget that it is in fact being put to good use.

There have been times at work where someone new comes in after the initial page creation and attempts to "clean up" the code, and removes the class that was the JS hook thinking it did nothing since it wasn't associated with any CSS styles.

That's my 2 cents.
-Nathan


--
You received this message because you are subscribed to the Google Groups "Object Oriented CSS" group.
To post to this group, send email to object-or...@googlegroups.com.
To unsubscribe from this group, send email to object-oriented...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/object-oriented-css?hl=en.




--
All the best,
Nathan Graves

Ad Taylor

unread,
Jan 10, 2012, 9:17:35 AM1/10/12
to object-or...@googlegroups.com
Well, ID's are great for JS hooks as they are faster (due the native getElementByID) although this consideration is maybe less of a concern in more modern browsers. 

The obvious benefit when using classes is that you can have multiple hooks… this can be useful for setting the state of a widget.

-- 
Ad Taylor
@iamadtaylor

aaron cavano

unread,
Jan 10, 2012, 9:47:42 AM1/10/12
to object-or...@googlegroups.com
You can always use HTML5 data attributes, but this obviously only supported in modern browsers. 

You can use the DOM .getAttribute() method and this will make it work in IE6+ and I believe could even work as far back to ie4 (if anyone cares). 

My personal preference is the custom data attribute or just use ids for js targets and classes for styles. 

Thanks,
Aaron Cavano

Ytterström Anders (Adeprimo)

unread,
Jan 10, 2012, 9:56:58 AM1/10/12
to <object-oriented-css@googlegroups.com>
I say, use whatever you want (elements, ids, classes) and keep doing so until _real_ problems occur or you have a site to test on. Premature optimization is bad often than it is good.

With a good testing environment, http://benchmarkjs.com/ or some benchmarking with console.log( new Date().getTime() ) can make it possible for you to decide what is best.

I have worked with sites with HTML documents counting 10k+ elements, on those it was really important to choose the correct hooks. Typically, though, 10k+ elements are extreme and "normal" sites are not really in any need of premature optimization.

If you want to read about it, consider Souders saying about it, for example:
http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/

Personally I prefer IDs for unique stuffs. Best of all, though, is to skip JavaScript as long as possible. :)

/ay

Ad Taylor

unread,
Jan 10, 2012, 10:07:10 AM1/10/12
to object-or...@googlegroups.com
It's also worth noting that http://jsperf.com is a pretty great tool for testing these things out on. I just made a quick example to show the difference in speed between some selectors http://jsperf.com/ids-classes-and-data-attributes

As was said before, it's not worth worrying about it too much now but it's good to be aware.

-- 
Ad Taylor
@iamadtaylor

Aeron Glemann

unread,
Jan 10, 2012, 10:39:12 AM1/10/12
to object-or...@googlegroups.com
I don't think being consistent with classes vs ID's is premature optimization. Refactoring CSS is incredibly difficult since there isn't any kind of automated testing (that I know of) to check that nothing breaks across browsers when changing HTML, CSS, renaming classes, changing specificity, etc.. there are a lot of variables at play.

Conventions and consistency are why frameworks (including OOCSS) are so popular.

My advice is to use CSS classes - and to a lesser extend elements - for styling hooks. And use ID's and classes prefixed with something like "js-" for Javascript hooks. If you are consistent with never styling ID's or the "js-" classes then it will be much easier to refactor later on. Especially not styling ID's helps avoid specificity wars, while using them for JS hooks takes advantage of the very fast native getElementById selector.

If you're familiar with HTML metadata, I'd bet a contributing factor why microformats were abandoned for HTML5 schemas (schema.org) was that microformats confused metadata with presentation. It was too easy to use the microformat classes for styling which made it much more difficult to change presentation or content without breaking one or the other.

Separation of concerns is a good thing.

2012/1/10 Ytterström Anders (Adeprimo) <Anders.Y...@adeprimo.se>

Dave Gregory

unread,
Jan 10, 2012, 8:05:32 PM1/10/12
to object-or...@googlegroups.com
I did a blog post about this about a year ago..    

I'd say that after working in OOCSS for more than 2 years now, a general rule that works for me is to:
1.  create default styling for all html elements
2.  extend the defaults with custom styles using classes
3.  use ID's sparingly, but there are places where they make sense.   Where you only want one instance per page. (layout code)

Now I say this only tailored toward CSS.    When doing Javascript, I usually ID the container of the code I'm working with, so I can take advantage speedy selectors (although I haven't tested nor looked into that speed)

here is the blog post:
(dont mind the title, I've since changed my stance a bit)

and the findings from the speed tests I did:

hope that helps

Dave.

Murray Nuttall

unread,
Jan 11, 2012, 12:04:28 AM1/11/12
to object-or...@googlegroups.com
In my experience ID's should be used for programming hooks only (JavaScript, Visual Studio, etc), and should never ever be referenced in style sheets.

In the past whenever I referenced an ID in my style sheet I have 100% regretted it. 

I wouldn't even consider using them for styling layout, or one-off things. 

Murray Nuttall

unread,
Jan 11, 2012, 1:36:04 PM1/11/12
to object-or...@googlegroups.com
Oh, yeah js- for JavaScript hooks is one of my favorites too.

I'm not sure if it's completely relevant to this topic, but I really like this presentation on using JavaScript with OOCSS. It describes extending OOCSS with live behavior classes. 



Sent from my iPad

Dave Gregory

unread,
Jan 12, 2012, 1:32:25 AM1/12/12
to object-or...@googlegroups.com
Hahahaha!  Love it!   thanks for that link! 

Dave

Eoin Kelly

unread,
Jun 30, 2012, 11:09:40 PM6/30/12
to object-or...@googlegroups.com
Hi Rick,
Class and ID names perform up to 3 jobs:
1. Provide a hook for CSS to apply style rules
2. Provide a hook for JS to find and manipulate the element on the page.
3. A small agreed-upon set of class names can provide extra information about the content a.k.a. Microformats (http://microformats.org/)

My current practice is based on two principles.

Principle #1: Each class or ID name should do only one job.
While it is possible to re-use a class/ID name for more than one task it's not a good idea because 
* It couples your HTML, CSS and JS tightly together. As an example, Let's say we have <div class="foo"> and are applying styles to and using it as a JS hook. If we later decide that the .foo{} styles are no longer appropriate for that div but we still want our JS to target it. Now we have to edit our JS as well as our CSS.
* It makes the intent of your code harder to deduce for other coders (even the future you). 

Principle #2: Each Job is different
Each Job has different criteria for deciding 
1. whether to use a class or ID as a hook
2. how to name your class or ID.

Job 1. [A hook for CSS]
OOCSS guides you here on how to name your classes and whether to use class or ID. My personal approach (YMMV) is 
* First style bare elements to provide reasonable defaults (I use normalize.css (http://necolas.github.com/normalize.css/) with a few per-site tweaks)
* Use classes (in the OOCSS style) to apply any further styling required. I never mix classes and elements in selectors. Andy Hume has an excellent presentation from SXSW Interactive last year where he discusses this issue with more clarity that I could (audio: http://schedule.sxsw.com/2012/events/event_IAP9410 and slides: https://speakerdeck.com/u/andyhume/p/css-for-grown-ups-maturing-best-practises

Job 2. [A hook for JS]
I prefix any class or ID I use as a JS hook with 'js-'. Use an ID if you need to uniquely identify the element, use a class-name if you need to target more than one element. Do whatever makes your code the most readable and easy to understand. Only do something different if you find an actual performance problem (see @madr comments on premature optimization earlier in this thread). JS engine and CSS selector performance vary a lot between browsers (and browser versions) so it is difficult to give definitive advice on the performance of classes versus IDs as JS hooks. There are differences but whether they are relevant is harder to answer. The best advice I have seen (and will echo here) is that you don't get to care about CSS/JS selector performance until you have covered all the "big win" front-end performance optimizations - proper caching, minimizing HTTP requests etc. -see https://developers.google.com/speed/ for the gory details.

Job 3 [Microformats]
Rules for naming defined at http://microformats.org/. @aglemann has mentioned that microformats confuse metadata with styling (I happen to agree with this) but they can be used safely & sanely as long as you consider the microformat class names "off-limits" to styling and JS.

HTH
/Eoin/

Aeron Glemann

unread,
Jul 1, 2012, 10:26:02 AM7/1/12
to object-or...@googlegroups.com
This is great advice (naturally I agree with all of it ;)

The only thing I would say about #3... is AFAIK microformats are being phased out in favor of schemas (http://schema.org/docs/schemas.html) which use custom attributes so you no longer are tempted to style those .fn classes ;)

In our case we have a #4:

4. Provide a hook for Selenium (automated QA testing) to find elements on the page.

Which ran into the same problem, where re-factoring CSS or JS un-necessarily broke the Selenium tests. Initially, I've treated this the same as JS: use either id's or classes prefixed with ".qa-" - the rationale there is:

- id's should never be changed. You might add an id to an element that doesn't have one, but so far haven't come across a case where it was necessary to rename an id affecting the JS or QA tests.
- CSS won't touch the .js- or .qa- classes. In fact seeing the class there alerts the developer that there is a test running on those elements so they will take care not to affect the test.

The downside to this, is we're being very defensive, but ending up with elements like:

<div class="review js-review qa-review">

etc, which doesn't feel right at all. So the other option would be to not have specific QA selectors, and just fix the broken tests everytime the markup changes - which happens to be a lot right now cause we're doing a re-platforming, but presumably shouldn't happen that often on a mature, stable site.

--
You received this message because you are subscribed to the Google Groups "Object Oriented CSS" group.

Eoin Kelly

unread,
Jul 1, 2012, 7:36:51 PM7/1/12
to object-or...@googlegroups.com

I hadn't considered hanging unit tests off separate classes but it makes sense - I'll try to adopt that in future. I know what you mean about

<div class="review js-review qa-review">

not "feeling" right. I used to feel the same way but these days I can't think of a single good reason not to do this (other than some sort of vague guilt about "classitis"). I can't speak for other devs but I grew up learning that classes and IDs should be named based on the content - we were told that class and ID names were an opportunity to endow your content with the magical pixie dust of semantics. But semantics is all about the relationship between symbols and meaning. And meaning depends on our audience - who is reading the code and what are they trying to get out of it. To my mind, our class and ID names are symbols that communicate to two audiences (ignoring microformats as a special case) 1. Our other code (the robots) 2. Other developers

Nobody else reads or cares about our class and ID names. For some reason it took me an inordinately long time to accept that last statement (not the sharpest tool in the box sometimes). Even now it still "feels" wrong but I haven't found any compelling evidence against it. And y'know what, our robots (other code) don't care about what names we use either! - the browser would be just as happy with

<div id="iuj" class="xgt fjl">

as long as our CSS and JS use the same symbols. So our only audience for class and ID names are other developers and the meaning they want to extract from our code is knowledge of how it is structured and how to safely make changes.

We could create a completely unique vocabulary for each site (rough analogy with an XML approach) but some sort of shared set of symbols that have an agreed upon meaning (the HTML approach) really speeds up communication. A sensible set of prefixes and clear separation of concerns goes a long way towards this I think. To my mind, this is one of the big wins of the OOCSS approach. Looking at

<div class="review js-review qa-review">

again, I can guess that this block is touched by JS and has at least one unit test associated with it and that the dev team that created it have labeled it a "review". Compare this with

<div class="review">

where I only learn that, in the vocabularly of the devs that created this page, this block is described as a "review" which doesn't tell me much, especially as in the real world it's likely to appear as

<div class="review">
  <h1>Review</h1>
  ...
</div>

I have heard folks argue that this approach bloats the markup - certainly the markup gets bigger but (in my experience at least) my CSS is much smaller and I would question how much of a real world performance problem of slightly bigger markup is provided it is served using gzip compression.

Thanks for your time.

/Eoin/

Bradley Few

unread,
Jul 2, 2012, 11:26:24 AM7/2/12
to object-or...@googlegroups.com
Hey, I tend to stick with classes using the 'js-' namespace for javaScript hooks and use data-attributes for DOM interaction.

Matthew Browne

unread,
Jul 2, 2012, 9:00:57 PM7/2/12
to object-or...@googlegroups.com
IDs are indeed preferred for Javascript hooks - they're the fastest way to get a reference to an element (using the document.getElementById() method). However, most modern browsers have Javascript functions that make CSS selector lookups very fast as well, as long as they're not too complicated.
--
You received this message because you are subscribed to the Google Groups "Object Oriented CSS" group.
Reply all
Reply to author
Forward
0 new messages