var querySelector = function(selector) { //TODO 先简单兼容,后续继续扩展;
var element = null;
if(document.querySelector) {
element = document.querySelector(selector);
} else {
var selectors = selector.split(' ');
var context = document;
for(var i = 0, len = selectors.length; i < len; i++) {
context = handleQuery(selectors[i], context);
}
element = context;
}
return element;
};
var handleQuery = function(selector, context) {
var idSelectorRE = /^#([w-]+)$/;
var classSelectorRE = /^.([w-]+)$/;
var tagSelectorRE = /^[w-]+$/;
var element = null;
if(idSelectorRE.test(selector)) {
element = context.getElementById(selector.substring(1));
} else if(classSelectorRE.test(selector)) {
element = context.getElementsByClassName(selector.substring(1))[0];
} else if(tagSelectorRE.test(selector)) {
element = context.getElementsByTagName(selector)[0];
}
return element;
};
这里关键的地方,在于处理多级选择器。不过,这里没有处理同级多类型选择器的情况,后续会补充。