Tuesday, November 6, 2012

Using class as jquery selector

We are so much used codes such as following,

$('a.mark_locked').live('click', function () {
  // your code goes here
});

Using class as a selector for putting a javascript business logic is kind of evil.
The purpose of class in HTML is for styling. After jquery or prototype came to light, people have been using it for selectors as well. But to me this is not right. I myself used to do this a lot. But not anymore. Because when you hire a designer to change the html or dom then the designer has to know which class to keep and which to change. He does not have a clue which are the classes used for javascript. And for a large project it is a huge issue. Eventually no classes are removed and the HTML dom becomes heavy and clumsy.

A much better approach is to use attribute selector, as following,
$('a[mark_locked]').live('click', function () {
  // your code goes here
});

Now your designer has more freedom for manipulating classes in dom.