1. Get DOM elements with one simple method
There is a cross-browser getElementById method of the document object, which
returns a reference to the object with the specified value of the ID attribute. Prototype
JavaScript Framework (http://www.prototypejs.org) provides a convenient JavaScript
method with a short name to return DOM elements:
function $() {
var elements = new Array();
for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); } return elements; }
One nice thing about this method is that you can pass either one argument or multiple
arguments. If one argument is passed it returns a reference to the object with the
specified ID value. Otherwise it returns an array of references to the objects with the
specified ID values. Another nice thing about this method is that it takes objects as well
as strings as arguments.
Instead of the following:
var elem = document.getElementById('TextBox1');
You can now call the $ method as follows:
var elem = $('TextBox1');
Or you can return multiple DOM elements with one simple method call:
var elemArr = $('TextBox1', 'TextBox2');
Monday, March 10, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment