function $
A while back, Bender sent me a link to a prototype.js file that pretty much claimed to be a web developers best friend. It certainly has some interesting features, and one that I really liked was the “$” function. Basically, the developer had written the function to return you an array of the elements that you asked for by id. So in effect, if you wrote -
var elements = $("txtName", "txtPhone", "txtCountry");
- then you would be returned an array containing a reference to each of those form elements (presuming that they exist, of course ;-))
Well that’s all fine and dandy, but more often than not I find myself trying to find elements in that are declared as: runat=”server”. And if those elements are nested in a UserControl, then you have to know how their id will be transformed at runtime by ASP.NET (for example, “txtName” may become “ctl00_main_sidebar_txtName”). So, with this in mind, I wrote my own version of the $ function which took care of this situation for me:
/*
* Find an element based on the provided strings
*
* elementId: Server-side id of the element to find (e.g. "txtName")
* tagName: The runtime tag of the element (e.g. "input")
* elementType: The runtime value of the "type" attribute for the element,
* if it exists (e.g. "text")
*/
function $(elementId, tagName, elementType) {
if (!tagName || tagName == "") {
return document.getElementById(elementId);
} else if (tagName) {
var elements = document.getElementsByTagName(tagName, "gi");
var typeRegex = elementType && elementType != "" ? new RegExp(elementType) : null;
for (var i = 0; i < elements.length; i++) {
if (typeRegex) {
if (!elements[i].type || !typeRegex.exec(elements[i].type)) {
continue;
}
}
if (elements[i].id && elements[i].id.indexOf(elementId) >= 0) {
return elements[i];
}
}
}
return null;
}
It’s possibly not the most efficient piece of code that you’ll ever come across, but it does the job perfectly.
And here is another solution that doesn’t require any knowledge of the tagname and type.