Skip to content

Instantly share code, notes, and snippets.

@hehongwei44
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hehongwei44/d608126f5b3407220932 to your computer and use it in GitHub Desktop.
Save hehongwei44/d608126f5b3407220932 to your computer and use it in GitHub Desktop.
简单的DOM的API封装
/*根据ID获取元素*/
var $id = function(id){
return document.getElementById(id);
};
/*根据标签名获取元素,返回元素的节点伪数组*/
var $tag = function(tagName, parent){
return (parent || document).getElementsByTagName(tagName);
};
/*根据样式名获取元素,返回元素的节点数组。其中className是必填项目*/
var $class = function (className, tagName, parent) {
//元素可能存在多个className,故匹配我们所需要的className
var re = new RegExp('(^|\\s)' + className + '(\\s|$)'), node = [];
if (arguments.length === 1) {
//只传入className
tagName = "*";
parent = document;
} else if (arguments.length === 2 && tagName.constructor === "String") {
//传入ClassName和节点类型
parent = document;
} else if (arguments.length === 2 && tagName.constructor !== "String") {
//传入ClassName和父亲节点
tagName = "*"
} else if (arguments.length === 3) {
//传入ClassName和节点类型以及父亲节点
}
var nodebyTag = parent.getElementsByTagName(tagName);
for (var i = 0; i < nodebyTag.length; i++) {
if (re.test(nodebyTag[i].className)) {
node.push(nodebyTag[i]);
}
}
return node;
}
@hehongwei44
Copy link
Author

后续拓展$class

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment