getElementById Problems in asp.net

9 May 2008
When using asp.net with control containers or master pages, the ID of the DHTML controls rendered on the client look something like 'ctl00$cphMain$btnFilter', this means accessing the known id 'btnFilter' with getElementById doesn't work. There are some asp.net workarounds for this such as
document.getElementById("<%= btnFilter.ClientID %>");
but I keep most of my Javascript in separate *.js files where I can't use asp.net.
The reason why asp.net is adding a prefix to the ID is to make sure the ID stays unique even when the control is used within a repeater or other databound control. In most of my cases however I do know that the ID I assigned is unique on the page and I needed an easy way to access the control in JavaScript.

My solution is to add a simple function to my common JavaScript code that is including on all pages so I can use it everywhere on the site.

The new function GetElementByTagAndPartialID which takes two parameters, the name of the tag such as 'input' or 'div' and the original ID. This function first gets a collection of all controls with the specified tag name on the page and then loops through them to return the first one that partially matches the ID given.
function GetElementByTagAndPartialID(tagname, partialID)
{
    
    var elementsWithTag = document.getElementsByTagName(tagname);
    var elementFound = null;
    
    if (elementsWithTag!=null)
    {
        for (i=0; i<elementsWithTag.length; i++) 
        {
            if (elementsWithTag[i].id.indexOf(partialID) > -1)
            {
                elementFound = elementsWithTag[i];
                break;
            } 
        }
    }

    return elementFound;
}
If the tag name is not known in advanced, one would have to loop through all DHTML controls on the page which would take a bit longer.

Pages in this section

Categories

ASP.Net | Community | Development | IIS | IT Pro | Security | SQL (Server) | Tools | Web | Work on the road | Windows