Quantcast
Channel: w3cplus
Viewing all articles
Browse latest Browse all 1557

js根据id,class,标签获取元素

$
0
0
var get = {
	byId: function(id) {
		return document.getElementById(id)
	},
	byClass: function(sClass, oParent) {
		if(oParent.getElementsByClass){
			return (oParent || document).getElementsByClass(sClass)
		}else{
			var aClass = [];
	  		var reClass = new RegExp("(^| )" + sClass + "( |$)");
	  		var aElem = this.byTagName("*", oParent);
	  		for (var i = 0; i < aElem.length; i++) reClass.test(aElem[i].className) && aClass.push(aElem[i]);
	  		return aClass
		}
	},
	byTagName: function(elem, obj) {
		return (obj || document).getElementsByTagName(elem)
	}
};

//实例
var oNav = get.byId("nav");
var aLi = get.byTagName("li", oNav);
var aSubNav = get.byClass("subnav", oNav);

Viewing all articles
Browse latest Browse all 1557

Trending Articles