How to: Access Controls from JavaScript by ID

One way to access a control from client script is to pass the value of the ClientID property of the server control to the document.getElementById method. The ClientID property value is rendered in HTML as the id attribute. To use this method, you must know how the ClientID value is generated. This document explains the algorithms that are available and how to select one.

To access a control from client script

  1. Add the control to a Web page or user control.

  2. Set the ClientIDMode property of the control to one of the following values:

  3. If you have set the ClientIDMode property to Predictable, set the ClientIDRowSuffix property to the name of the data field that you want to use to uniquely identify each instance of the control. For the GridView control, you can enter multiple field names separated by commas.

    If you do not set the ClientIDRowSuffix property, ASP.NET uses a sequential number as the ClientID suffix. This is similar to the algorithm used for AutoID, except that the number is placed at the end of the generated ID instead of before the control's ID. In addition, the sequential number appears without a ctrl prefix (for example, the ClientID would be Container_Control_25 instead of Container_ctrl25_Control).

  4. In client script, use the document.getElementById method and pass to it the ClientID value that will be generated by the algorithm you selected.

    The following example shows a user control that contains a Label control with the ClientIDMode property set to Static. The user control also contains client script that accesses the control by its ID. Because the ClientIDMode property is set to Static, this user control can be used in any container control and have the same value for the ClientID property.

    <%@ Control AutoEventWireup="true" %>
    <script type="text/javascript">
      var seasonalSports = new Array("None selected",
      function DisplaySport(x) {
          = seasonalSports[x];
    <asp:DropDownList ID="DropDownList1" runat="server" 
      <asp:ListItem Value="Select a season"></asp:ListItem>
      <asp:ListItem Value="Spring"></asp:ListItem>
      <asp:ListItem Value="Summer"></asp:ListItem>
      <asp:ListItem Value="Autumn"></asp:ListItem>
      <asp:ListItem Value="Winter"></asp:ListItem>
    <br />
    <asp:Label ID="SelectedSport" runat="server" ClientIDMode="Static">

See Also


Walkthrough: Making Data-Bound Controls Easier to Access from JavaScript

Walkthrough: Making Controls Located in Web User Controls Easier to Access from JavaScript






ASP.NET Web Server Control Identification