02 October, 2009

LINQ to Javascript - make a Where

I find LINQ very cool for Data querying.

I tried to code a Where function for Javascript Arrays :

Array.prototype.where = function(condition) {
var list = [];
for (var i=0; i < this.length; i++) {
if ( condition.call(this[i]) ) {
if ( list.length == 1) {
return list[0];
else {
return list;

You havre to send a "condition" function in the where that will test each element and return an array contained elements that verify the condition.

The context of the condition is the element itself so you can easily access it with "this".

Suppose you have INPUT form elements in your document and you want to retrieve those which id contains "browserWidth".

Here is the code :

function() {
return (this.id.indexOf('serviceSelected') != -1);

If the return array contains a single element, it returns the element itself.

Access C#.NET Server controls by id on client side

In C#.NET, when you declare a Control runat="server", the id of the Control is not the same on the client side.

For example, a Control named "browserWidth" on the server side will have the following id on the client side : "ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder1_browserWidth".

Thus, you can't access it with a classic Javascript $("browserWidth"), and it is very difficult to guess what client id the Control will have.

My best hack for that is to use the "class" attribute, that can be multiple, and add a class which name is the same as the id of the Control, like this : class="browserWidth" or CssClass="browserWidth" if you work with an asp.net Control.

This way, I can access my client control with Javascript $$("*.browserWidth")[0].

The only problem comes with the asp:HiddenField Control that doesn't accept CssClass attribute.

On the client side, I have a tricks to access to it :

$$('input').where(function() { return (this.id.indexOf("browserWidth") != -1); })

The "where" fucntion is one of mine explain in the next Post.

This tricks works under two conditions :

- your Control has a unique ID
- the Server ID of the Control is contained in the client ID "ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder1_browserWidth"

If M$ changes the way client ID are made and decides to not add server control id at the end, that tricks would not work.