Last active
August 29, 2015 14:01
-
-
Save jdrury/cf1d64d9c8b91eb8e07a to your computer and use it in GitHub Desktop.
DOM traversing element selector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var $ = function (selector) { | |
var tree = traverse(document.body.children); | |
var search = format(selector); | |
var labels = ['nodeName', 'className', 'id']; | |
var elements = []; | |
var match; | |
tree.forEach(function(node) { | |
match = true; | |
search.forEach(function(query, i) { | |
if (query) { | |
if (node[labels[i]].toLowerCase().indexOf(query) === -1) { | |
match = null; | |
} | |
} | |
}); | |
if (match) { | |
elements.push(node); | |
} | |
}); | |
return elements; | |
}; | |
function traverse(dom) { | |
var results = []; | |
for(var i = 0; i < dom.length ; i++) { | |
results.push(dom[i]); | |
} | |
return results; | |
} | |
function format(selector) { | |
var search = []; | |
var temp; | |
var blueprint = { | |
selectorTag: '', | |
selectorClass: '', | |
selectorId: '' | |
}; | |
if (selector.indexOf('.') !== -1 && selector.indexOf('#') !== -1) { | |
if (selector.indexOf('#') > selector.indexOf('.')) { | |
blueprint.selectorTag = selector.split('.')[0]; | |
temp = selector.split('.')[1]; | |
blueprint.selectorClass = temp.split('#')[0]; | |
blueprint.selectorId = temp.split('#')[1]; | |
} else if (selector.indexOf('#') < selector.indexOf('.')) { | |
blueprint.selectorTag = selector.split('#')[0]; | |
temp = selector.split('#')[1]; | |
blueprint.selectorClass = temp.split('.')[1]; | |
blueprint.selectorId = temp.split('.')[0]; | |
} | |
} else if (selector.indexOf('.') !== -1 && selector.indexOf('#') === -1) { | |
blueprint.selectorTag = selector.split('.')[0]; | |
blueprint.selectorClass = selector.split('.')[1]; | |
} else if (selector.indexOf('#') !== -1 && selector.indexOf('.') === -1) { | |
blueprint.selectorTag = selector.split('#')[0]; | |
blueprint.selectorId = selector.split('#')[1]; | |
} else { | |
blueprint.selectorTag = selector; | |
} | |
for (var key in blueprint){ | |
search.push(blueprint[key]); | |
} | |
return search; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment