jasmine214--love

只有当你的内心总是充满快乐、美好的愿望和宁静时,你才能拥有强壮的体魄和明朗、快乐或者宁静的面容。
posts - 731, comments - 60, trackbacks - 0, articles - 0

document.getElementsByClassName自己写

Posted on 2010-06-16 12:10 幻海蓝梦 阅读(1656) 评论(0)  编辑  收藏 所属分类: JS

http://www.qihangnet.com/PermaLink,guid,1b1d9be5-aa76-4e0d-9ac6-f52ae9505111.aspx
http://www.xiujie.cn/blog/post/41.html?bbs.xiujie.cn

document没有这个方法,

但是我们可以自己写

function getElementsByClassName(className, parentElement){
var elems = ($(parentElement)||document.body).getElementsByTagName("*");
var result=[];
for (i=0; j=elems[i]; i++){
   if ((" "+j.className+" ").indexOf(" "+className+" ")!=-1){
result.push(j);
   }
}
return result;
}
既然有getElementsByClassName,一样可以有 getElementsByAttribute(如:getElementsByValue、getElementsByStyle、getElementsByType)
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);


只有注册用户登录后才能发表评论。


网站导航: