function $() {
var elements = [];
var e = null;
for (var i = 0; i < arguments.length; i++) {
var element = null;
var arg = arguments[i];
if (typeof arg == 'string') {
element = document.getElementById(arg);
if (element === null) {
element = document.getElementsByTagName(arg);
if (element.length == 1) {
element = element[0];
}
}
if (element.length === 0) {
element = document.getElementsByName(arg);
/* note: IE does not return this as an array so only the first element
in the collection (only if more than one exists) will be accessible.*/
if (element.length === 1) {
element = element[0];
}
e = element;
}
} else {
element = arg;
}
if (arguments.length == 1) {
return element;
}
if (element !== null) {
elements.push(element);
}
}
return elements;
}
Usage
Accessing an element by id:
document.getElementById('id').innerHTML = 'Hello World';
With the dollar function would be:
$('id').innerHTML = 'Hello World';
Accessing an element by name:
document.getElementByName('name').innerHTML = 'Hello Tokyo';
With the dollar function would be:
$('name').innerHTML = 'Hello Tokyo';
Accessing more than one element at a time:
for (var i = 0; i < 2; i++) {
$('name1', 'name2')[i].innerHTML = "test";
}
Compress this code here
No comments:
Post a Comment