SharePoint and getElementById()

I’ve just found out that using JavaScript’s getElementById() function doesn’t quite work as expected when dealing with controls on SharePoint pages. This is because SharePoint uses its own identifiers, so¬†TextBox1 becomes something like ctl00$ctl00$g_3f6d90e4_335b_467c_a53f_6ae00bca6b63$ctl00$TextBox1.

Fortunately there’s a simple solution – instead of the following (which will cause an “Object required” JavaScript error):


you need to use this, which will insert the correct full ID for the element and thus work correctly:

document.getElementById("< %=TextBox1.ClientID%>");

It gets a bit more complicated when using nested controls, which is explained in this post by Eric Shupps.

If you enjoyed this post, please share it!

    3 comments on “SharePoint and getElementById()

    1. Testing says:

      This does not work for me since the field is NULL before finish loading the page.

    2. Chris Barnes says:

      Try moving the JavaScript code further down the page, or if using jQuery, put it within the document ready handler.

    Comments are closed.