ADSENSE HERE!
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.
ADSENSE HERE!
If behaviour and styling are related, which would seem likely in the last example, then I don't see any reason for seperate classNames.
ReplyDeleteI use 'js' prefixes as well though, but only for classNames that are added by JavaScript to give an element a certain state. With this prefix it should be clear for other developers, when looking at the stylesheet for instance, why certain classNames can not be found in the HTML templates.
[...] is the original post: DOM element class – css reference or javascript reference? – Web … If you enjoyed this article please consider sharing [...]
ReplyDeletejQuery UI uses this technique.. except it's ui- instead of js-.
ReplyDeleteBut yeah.. overall it avoids lots of headaches :)
mayhaps using classes only for styling while using data-xxxx attributes will make it cleaner?
ReplyDeleteThat's definitely match easier to reference by class with selectors in any js framework. Not sure that data-xxx selector will be as good as class selector.
ReplyDelete