Skip to content

Instantly share code, notes, and snippets.

@relaxedtomato
Created March 5, 2015 20:12
Show Gist options
  • Save relaxedtomato/71041894afc2f1598ee4 to your computer and use it in GitHub Desktop.
Save relaxedtomato/71041894afc2f1598ee4 to your computer and use it in GitHub Desktop.
selector.js
var traverseDomAndCollectElements = function(matchFunc, startEl) {
var resultSet = [];
if (typeof startEl === "undefined") {
startEl = document.body;
}
// your code here
// traverse the DOM tree and collect matching elements in resultSet
// use matchFunc to identify matching elements
return resultSet;
};
// detect and return the type of selector
// return one of these types: id, class, tag.class, tag
//
var selectorTypeMatcher = function(selector) {
// your code here
if(selector.indexOf('#') != -1 ){return 'id';}
if(selector.indexOf('.') === 0 ){return 'class';}
if(selector.indexOf('.') > 0 ){return 'tag.class';}
return 'tag';
};
// NOTE ABOUT THE MATCH FUNCTION
// remember, the returned matchFunction takes an *element* as a
// parameter and returns true/false depending on if that element
// matches the selector.
var matchFunctionMaker = function(selector) {
var sel = selector;
var selectorType = selectorTypeMatcher(selector);
var matchFunction;
if (selectorType === "id") {
// define matchFunction for id
matchFunction = function(element){
// debugger;
if(!element.id){return false;}
return element.id.toLowerCase() === sel.toLowerCase().slice(1,sel.length);
}
} else if (selectorType === "class") {
matchFunction = function(element){
if(element.classList.length === 0){return false;}
// element.classList.some(function(classItem){
// debugger;
// return classItem.toLowerCase() === sel.toLowerCase().slice(1,sel.length);
// });
for(prop in element.classList){
if(element.classList[prop].toLowerCase() === sel.toLowerCase().slice(1,sel.length)){
return true;
}
}
return false;
}
// define matchFunction for class
} else if (selectorType === "tag.class") {
matchFunction = function(element){
if (element.tagName.toLowerCase() === sel.toLowerCase().slice(0,sel.indexOf('.'))){
if(element.classList.length === 0){return false;}
for(prop in element.classList){
// debugger;
if(element.classList[prop].toLowerCase() === sel.toLowerCase().slice(sel.indexOf('.')+1,sel.length)){
return true;
}
}
}
return false;
}
} else if (selectorType === "tag") {
// define matchFunction for tag
matchFunction = function(element){
return element.tagName.toLowerCase() === sel.toLowerCase();
}
}
return matchFunction;
};
var $ = function(selector) {
var elements;
var selectorMatchFunc = matchFunctionMaker(selector);
elements = traverseDomAndCollectElements(selectorMatchFunc);
return elements;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment