How to handle ctl00_ContentPlaceHolder in JavaScript

If you develop in ASP.NET, you’ll notice when you run your web app, that your server side components get a name similar to “ctl00_ContentPlaceHolder” prepended to the name you assigned them.  To further frustrate things, that prefix is not guaranteed to be that from build to build.  So, how do you reference such an object from JavaScript?

Assume you have an image object on your page.  At design time, the HTML for the image might look like this:

<

asp:Image ID="LogoImage" runat="server" ImageUrl="~/Images/logo.png" />

Here’s a “compiled” and running HTML version of what an object might look like in the runtime HTML:

<img id="ctl100_ContentPlaceHolder1_LogoImage" src="/Images/logo.png" style="border-width:0px"/>

The problem is you don’t want to reference the object in JavaScript like this:

document.getElementById("ctl100_ContentPlaceHolder1_LogoImage")

Instead, do this:

document.getElementById("<%=LogoImage.ClientID%>")

Now your JavaScript is guaranteed to work even if the prefix changes with later compiles or updates to Visual Studio.

Leave a Reply