Thursday, July 9, 2009

Adding classes to elements to assist jQuery

As I start using jQuery more and more I'm finding myself wanting to select elements on a page based on criteria that original come from the database records that generated the data for those elements.

I am currently working on a project to convert classic ASP Snitz forum software to ASP.NET MVC and I'm moving all the JavaScript to jQuery while I'm doing this. As with most forums, this forum has a subscription option which allows the user to subscribe to the entire board, a category on the board, a forum in a category, or an individual topic.

As such, subscribe and unsubscribe icons and anchor text litter most pages. My first attempt at coding this had most of the which-icon-do-we-display logic on the server and then jQuery ajax changed the buttons and performed actions when these icons were clicked which caused small amounts of code to be duplicated in JavaScript and C#.

My current iteration has the server mark the elements with classes and then have all the manipulation done on the client using jQuery. I've identified 4 classes which are synonymous with data fields that I'm using to find the right elements:

CollectionType: This can only hold the value subscription and identifies this element as an anchor for subscriptions.

DataType: Can be one of board, category, forum, or topic. Identifies the type (or level) of subscription.

Active: Can be one True or False. Note the proper case. These values are generated by the toString() function from booleans.

ID: This is a number such as 4102 which is the ID of the category, forum or topic to identify the exact record in the DB. The data type of board would not have anything here.

If I want to find all of the subscription icons on a page that are active then I can use:


all topics would be:


and a specific topic would be:


It feels wrong to be using ID's as classes but this certainly seems to make the query part of jQuery work very well. Likewise, putting 'True' and 'False' in as css classes seems wrong.

Anybody have a better solution for this?


  1. Hey Guy,
    Have you looked into making custom jQuery selectors? Not sure if it will help you in this case, but it seems like you are using a custom selector pattern without the selectors...

  2. Hey Saul - Looks interesting. In this particular case it won't help but I'm sure that neat little piece of code you wrote is going to be useful for me soon - thanks!