Sunday, January 22, 2012

Are You Still Parsing HTML Element Ids?

To render a list, often times we use repeated HTML elements with a similar template. For example, the search results in ebay.com is a list of divs, each containing different data in the same template. In a server side, this rendering code is somewhat similar to this:


If you noticed, a product with it's database id = 123 will be rendered inside a div with id="product_123", and similarly div id="product_456" will contain the product with id = 456.

With such ids, we can write JavaScript code that can extract the database id of a selected product to do interesting things, for example:


This is a useful and a common technique. However, in this era of HTML5, we can make use of its custom attributes feature to write a clean JavaScript event handler without the help of parsing. Here's an example:


I will never parse my HTML element Id again. What about you?