欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

获取DOM对象的几种扩展及简写_javascript技巧

程序员文章站 2022-04-05 23:28:22
...
参照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 var child = children[ii];
var classNames = child.className.split(' ');
for (var j = 0; 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 if (children[ii].type == sTypeValue) {
elements.push(children[ii]);
}
}
return elements;
}

function $() {
var elements = new Array();
for (var ii = 0; 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);
};