First look at an example
The code is as follows |
Copy Code |
/* * Get the element collection based on the element clsssname * @param fatherid The ID of the parent element, default to document * @tagName the label name of the child element * @className className strings separated by spaces */ function Getelementsbyclassname (fatherid,tagname,classname) { node = Fatherid&&document.getelementbyid (Fatherid) | | Document TagName = TagName | | "*"; ClassName = Classname.split (""); var classnamelength = classname.length; for (Var i=0,j=classnamelength;i<j;i++) { To create a regular that matches a class name classname[i]= New RegExp ("(^|\s)" + Classname[i].replace (/-/g, "\-") + "(\s|$)"); } var elements = Node.getelementsbytagname (tagName); var result = []; for (Var i=0,j=elements.length,k=0;i<j;i++) {//Cache length Property var element = Elements[i]; while (Classname[k++].test (element.classname)) {//Tuning loop if (k = = classnamelength) { Result[result.length] = element; Break } } k = 0; } return result; } |
OK, let's test this out:
The code is as follows |
Copy Code |
<div id= "Container" > <span class= "AAA zzz CCC" ></span> <div class= "AAA BBB CCC" ></div> </div> <div class= "AAA BBB CCC" ></div> |
Get the results right.
Some people will ask, the native method invocation efficiency is the highest, there are many browsers already will implement the Getelementsbyclassname this method, why does this place not first call the native and then call the custom?
Yes, the primary efficiency is very high, it supports multiple class conditions of the query, but the biggest problem is that he does not support getelementsbyclassname ("container", "div", "AAA CCC"), This finds the specified element in the specified label as the specified class. Therefore, the native method invocation is discarded here.
Example 2
The code is as follows |
Copy Code |
function GetClass (tagname,classname)//Get the element with label name TagName, class name ClassName { if (document.getelementsbyclassname)//support for this function {return document.getelementsbyclassname (className); } Else {var tags=document.getelementsbytagname (tagName);//Get Label The Var tagarr=[];//is used to return the element with the class name classname for (Var i=0;i < tags.length; i++) { if (Tags[i].class = = className) { Tagarr[tagarr.length] = tags[i];//Save the element that satisfies the condition } } return Tagarr; } } |