CSS Class Names Instead of ASP.NET Client IDs

In ASP.NET the client IDs of controls are often really unpredictable. When you need to add some JavaScript code that works with rendered controls you have to know their IDs. But usually an ID looks like something like this: “ctl00_contentBody_txtStreet”. There are several methods for overcoming that difficulty explained here. However they require writing additional code or even creating your own controls inherited from the original ones.

But there is one simply but yet dirty way of addressing HTML elements rendered by ASP.NET. Do you remember that you can assign the CssClass attribute to any server control? Do you remember the jQuery selector that allows you to retrieve the elements with the specified CSS class? So, we can use it!

The pattern is simple:

<asp:TextBox ID="txtStreet" runat="server" CssClass="txtStreet" />

You just add the CssClass attribute and give it a unique value. Then you can retrieve the value of the element or perform any other manipulation with jQuery:


Pretty simple. Although you must remember that it can take some time in case you have a long page because it will look through all the HTML tags to find the one with the given class name. At the same time for fast execution you can specify which elements to look for, you can simply add a tag name before, for instance “input” or a jQuery attribute – “:input”:

Mike Borozdin (Twitter)
26 February 2009

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way. My personal thoughts tend to change, hence the articles in this blog might not provide an accurate reflection of my present standpoint.

© Mike Borozdin