仿Jquery选择器

2018/7/25 10:55:27 人评论 次浏览 分类:选择器

(function() {
		function get_elements_by_class(search_class, node, tag) {
			var elements = [],
			eles,
			pattern = new RegExp('(^|\\s)' + search_class + '(\\s|$)');

			node = node || document;
			tag = tag || '*';

			eles = node.getElementsByTagName(tag);
			for (var i = 0; i < eles.length; i++) {
				if (pattern.test(eles[i].className)) {
					elements.push(eles[i]);
				}
			}

			return elements;
		}

		function $(selector, node) {
			var elements;

			node = node || document;
			if (document.querySelectorAll) {
				elements = node.querySelectorAll(selector);
			} else {
				switch (selector.substr(0, 1)) {
				case '#':
					elements = [node.getElementById(selector.substr(1))];
					break;
				case '.':
					if (document.getElementsByClassName) {
						elements = node.getElementsByClassName(selector.substr(1));
					} else {
						elements = get_elements_by_class(selector.substr(1), node);
					}
					break;
				default:
					elements = node.getElementsByTagName();
				}
			}
			return elements;
		}
		window.$ = $ || null;

})();


上一篇:没有了

下一篇:没有了