Skip to content

Instantly share code, notes, and snippets.

@elvingm
Last active August 29, 2015 14:13
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 elvingm/729a50d81a908e678afa to your computer and use it in GitHub Desktop.
Save elvingm/729a50d81a908e678afa to your computer and use it in GitHub Desktop.
Javascript Selection Engine without using querySelector or querySelectorAll
var $ = function (selector) {
var splitSelector = selector.split(/(?=\.)|(?=#)/);
/* elemAttributes object provided for:
1) DOM NodeName - only grabbing the first matched
2) List of classes
3) List of ID's - only grabbing the first matched
pushes result in corresponding array in elemAttr object
elName & classList use an array to capture all values provided
*/
var elemAttributes = { elName: [], idName: [], classList: [] };
splitSelector.forEach(function(subStr) {
if (subStr.charAt(0) === '#') {
elemAttributes.idName.push(subStr.substr(1));
} else if (subStr.charAt(0) === '.') {
elemAttributes.classList.push(subStr.substr(1));
} else {
elemAttributes.elName.push(subStr.toUpperCase());
}
});
var filterById = function(nodes) {
var matchedId = [];
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].id === elemAttributes.idName[0]) {
matchedId.push(nodes[i]);
break;
}
}
return matchedId;
};
var filterByClasses = function(nodes) {
var matchedClasses = [];
for (var i = 0; i < nodes.length; i++) {
var nodeClassList = nodes[i].className.split(' ');
for (var j = 0; j < nodeClassList.length; j ++) {
// search for class in classList array
if (elemAttributes.classList.indexOf(nodeClassList[j]) !== -1) {
matchedClasses.push(nodes[i]);
break;
}
}
}
return matchedClasses;
};
var filterByTagName = function(nodes) {
var filtered = [];
if (elemAttributes.idName.length > 0) {
filtered = filtered.concat(filterById(nodes));
} else if (elemAttributes.classList.length > 0) {
filtered = filtered.concat(filterByClasses(nodes));
} else {
filtered = filtered.concat(nodes);
}
return filtered;
};
var getElements = function() {
var nodes, elements = [];
if (elemAttributes.elName.length > 0) {
nodes = document.getElementsByTagName(elemAttributes.elName[0]);
nodes = filterByTagName([].slice.call(nodes));
} else if (elemAttributes.idName.length > 0) {
nodes = document.getElementById(elemAttributes.idName[0]);
} else if (elemAttributes.classList.length > 0) {
var classList = elemAttributes.classList.join(' ');
nodes = document.getElementsByClassName(classList);
nodes = [].slice.call(nodes); // transforms HTMLCollection to array
}
elements = elements.concat(nodes);
return elements;
};
return getElements();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment