Return to Snippet

Revision: 23770
at February 12, 2010 13:37 by erintechspired


Initial Code
//-----------------------------------------------------------------
//Usage: Returns the first instance of a DOM Element that contains the
//  desiredElementId. Useful if your framework appends to IDs, instead of
//  IE: myElement, you have ct001_myElement
//Parameters:
//  desiredElementId - The id to search for
//  tagName - (Optional) The tag name of elements to get.
//  (If you know your element is a div, for example, search only divs.)
//-----------------------------------------------------------------
function getElementBySimilarId(desiredElementId, tagName) {
    var elems;
    var returnElem = null;
    //Get all elements of the correct type
    if (tagName == null || tagName == '') {
        elems = document.getElementsByTagName('*');
    }
    else {
        try {
            elems = document.getElementsByTagName(tagName);
        }
        catch (e) {
            alert(type + ' is not a valid tagName/Element Type');
        }
    }
    //iterate through the elements
    for (var i = 0; i < elems.length; i++) {
        if (elems[i].id.indexOf(desiredElementId) > -1) {
            returnElem = elems[i];
            break;
        }
    }
    return returnElem;
}

Initial URL
http://techspired.com

Initial Description
A simple, non-recursive function that I use to return the first element with an ID that contains a certain ID string. 
Sometimes, APS.NET appends the Naming Container ID to the IDs of controls, and in instances where the ClientID of a control you want is not available, you can use this script to find the element you want by similar id. 
Dirty, but works most of the time for me.

Initial Title
getElementBySimilarId

Initial Tags
DOM, aspnet

Initial Language
JavaScript