参照prototype.js中getElementsByClassName的思想,扩展出几种在DEOM操作中可经常用到的获取对象的方法,使用获取对象变得更方便、更精确了:
document.getElementsByClassName = function(className,oBox) {
//适用于获取某个HTML区块内部含有某一特定className的所有HTML元素
this.d= oBox || document;
var children = this.d.getElementsByTagName('*') || document.all;
var elements = new Array();
for (var ii = 0; ii < children.length; ii++) {
var child = children[ii];
var classNames = child.className.split(' ');
for (var j = 0; j < classNames.length; j++) {
if (classNames[j] == className) {
elements.push(child);
break;
}
}
}
return elements;
}
document.getElementsByType = function(sTypeValue,oBox) {
//适用于获取某个HTML区块内部同属于某一特定type的所有HTML元素,如:input,script,link等等
this.d= oBox || document;
var children = this.d.getElementsByTagName('*') || document.all;
var elements = new Array();
for (var ii = 0; ii < children.length; ii++) {
if (children[ii].type == sTypeValue) {
elements.push(children[ii]);
}
}
return elements;
}
function $() {
var elements = new Array();
for (var ii = 0; ii < arguments.length; ii++) {
var element = arguments[ii];
if (typeof element == 'string')
element = document.getElementById(element);
if (arguments.length == 1)
return element;
elements.push(element);
}
return elements;
}
$Cls = function (s,o){
return document.getElementsByClassName(s,o);
};
$Type = function (s,o){
return document.getElementsByType(s,o);
};
$Tag = function (s,o){
this.d=o || document;
return this.d.getElementsByTagName(s);
};
$Name = function (s){ //通过name的方式只能针对整个document而言,不能为其限定范围
return document.getElementsByName(s);
};
dom对象
dom
扩展