Last active
October 12, 2015 10:48
-
-
Save rainyjune/4015368 to your computer and use it in GitHub Desktop.
DOM 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
//Returns an object reference to the identified element. | |
function id(i){ | |
return document.getElementById(i); | |
} | |
//Returns a list of elements with the given tag name. | |
function tagName(t){ | |
return document.getElementsByTagName(t); | |
} | |
//Returns a list of elements with the given name. | |
function name(n){ | |
return document.getElementsByName(n); | |
} | |
//Returns a set of elements which have all the given class names. | |
function className(classname, parentNode) { | |
var parentNode = parentNode || document; | |
if(document.getElementsByClassName) return parentNode.getElementsByClassName(classname); | |
var classnameArr = classname.replace(/^\s+|\s+$/g,"").split(/\s+/); | |
if(document.querySelectorAll) { | |
var classname = "." + classnameArr.join("."); | |
return parentNode.querySelectorAll(classname); | |
} | |
var allTags = parentNode.getElementsByTagName("*"); | |
var nodes = []; | |
if(allTags.length) { | |
tagLoop: | |
for(var i = 0; i < allTags.length; i++) { | |
var tmpTag = allTags[i]; | |
var tmpClass = tmpTag.className; | |
if(!tmpClass) continue tagLoop; | |
if (tmpClass === classname) { | |
nodes.push(tmpTag); | |
continue tagLoop; | |
} | |
matchLoop: | |
for(var j = 0; j < classnameArr.length; j++) { | |
var patt = new RegExp("\\b" + classnameArr[j] + "\\b"); | |
if(!patt.test(tmpClass)) { | |
continue tagLoop; | |
} | |
} | |
nodes.push(tmpTag); | |
} | |
} | |
return nodes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment