Bogdan Gusiev's blog

How to make good software for people

DOM element class - css reference or javascript reference?
20 Apr 2010

Designer have used element class attribute for CSS styling for ages. Nowadays classes are also used in javascript selectors. This overlapping cause additional problems: Changes in js may cause broken design and changes in design may cause broken js. The last one may be hard to detect especially when design and css are handled by different person.
Element class seems the best way to query the element from DOM in js code. Other variants like it's relative possition to other elements are very fragile. Let's say that we have the following DOM:
<a> Delete</a>
<a> Edit</a>
And both links are handled with javascript. How would you separate them?
  • By order(first, second) will cause problems if designer would like to change the order.
  • By id will fail if you would have a list of elements where each has these links
  • By label is just a fuck up and won't work for multi language application
The only one variant that provide the best stability is reference By class. But as stated above class also serves for another purpose - styling. The thing that might help is a special prefix(for example "js") for all 'JavaScript classes'. Like:
<a class="js-new-comment big-blue-button"> New Comment </a>
And the convention that classes with prefix should only be used in javascript selectors and classes without prefix in CSS.

Yes, sometimes it may look like:
<input type='button' class="js-follow-button follow-button"> Follow this person </input>
But that makes sense to eliminate maintenance problem described above.

javascript html dom css class element