I came up with this because i have been frustrated with trying to access ASP server objects through Javascript code. Because ASP changes the ID for ASP controls in many cases, the ID you use is not the one you access through Javascript. You can use server side
code (<%= ASPControl.ClientID %>), but it makes it more difficult to make reusable code doing this and i've had trouble with linking javascript with server-side code. So i've piggy-backed a little on the MS AJAX $get(element) command and made the following
script:
function getASPElm(nm,tag) {
if ($get(nm)) { return $get(nm); }
if (!tag) { var tag = '*'; }
var e = document.getElementsByTagName(tag);
for (var i=0; i < e.length; i++) {
if (e[i].id) {
if (e[i].id.indexOf(nm) != -1) {
return e[i];
}
}
}
return null;
}
First it looks to see if it finds the element using the MS AJAX $get function. If not, if you included an HTML tag it will get a list of objects with that tag, if not it will get a list of all objects. Then it will cycle through them until it finds the item
you specified. It's not perfect - but it works well for me. I bet someone could come up with something better though...
jsearles
Member
337 Points
91 Posts
Javascript Get ASP Element by ID
May 05, 2007 03:13 AM|LINK
function getASPElm(nm,tag) {
if ($get(nm)) { return $get(nm); }
if (!tag) { var tag = '*'; }
var e = document.getElementsByTagName(tag);
for (var i=0; i < e.length; i++) {
if (e[i].id) {
if (e[i].id.indexOf(nm) != -1) {
return e[i];
}
}
}
return null;
}
First it looks to see if it finds the element using the MS AJAX $get function. If not, if you included an HTML tag it will get a list of objects with that tag, if not it will get a list of all objects. Then it will cycle through them until it finds the item you specified. It's not perfect - but it works well for me. I bet someone could come up with something better though...