Javascript Function to get control using Server Side ID

I don’t remember how many times I have written this, nearly for every ASP.NET project I have to write this, so I am posting so I can get it back. It is a simple method of the getting the control with the server side id. ASP.NET changes the Id’s of nested server side controls when page is rendered.

This function simply compares the last part of the control id with the server side id of the control (passed as parameter)

function findObjWithClientId(Id)

{

var ctrls = document.all;

for(var count = 0; count < ctrls.length ; count ++)

{

var index = ctrls[count].id.indexOf(Id);

if(index != -1)

{

if((ctrls[count].id.length – index) == Id.length)

{

return ctrls[count];

}

}

}

return null;

}

Advertisements

7 thoughts on “Javascript Function to get control using Server Side ID

  1. Dan,

    Becuase document.getElementById() will only return the control if I pass the correct client side Id to the control. The problem is that Ihave only Server Side Id. The Client Id will be rendered by ASP.NET. If you notice the function actually checks the part of the control Id.

  2. This won’t work in Firefox because it doesn’t like document.all, to get it to work in firefox replace the following line…

    var ctrls = document.all;

    With this…

    var ctrls = document.getElementsByTagName(“body”)[0].getElementsByTagName(“*”);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s