Sohan's Blog

Living the Developer's Life

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 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?


nice!, I didt know this function, tks for sharing!
In my point of view You sure did put a new twist on something that Ive heard so much about ActualExams. And How did you manage to make a blog that as smart as it is sleek?