JavaScript Getelementsbyclassname implements code _javascript tips

Source: Internet
Author: User
Tags tagname
Let's take a look at the code: (Supports multiple class queries and queries within a range)
Copy Code code as follows:

/*
* 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:
Copy Code code as follows:

<div id= "Container" >
<span class= "AAA zzz CCC" ></span>
<div class= "AAA BBB CCC" ></div>
</div>
<div class= "AAA BBB CCC" ></div>

Copy Code code as follows:

Window.onload = function () {
Alert (Getelementsbyclassname (document, "div", "AAA CCC"). length);//2
Alert (Getelementsbyclassname ("container", "div", "AAA CCC"). length);//1
Alert (Getelementsbyclassname ("container", "span", "AAA zzz"). length);//1
}

Get the results right.
The getelementsbyclassname of the native
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.
On the problem of cycle optimization
In the code, you'll see that I cache the length of the array, which can improve efficiency. In fact, there is a very subtle problem here, that is, the array access length property and htmlcollection access length are very different. In the array, length is a normal property, Access does not take extra action, in the view of htmlcollection, we often use htmlcollection as an array, but in fact, it is a DOM structure automatically changes in entity objects. Each time a Htmlcollection object's properties are accessed, he makes a complete match of all the nodes in the DOM. That is, the collection object is updated once every time the length of the Htmlcollection object is accessed, and the performance is very high. So in general, this htmlcollection loop operation is recommended to cache length.
The Extra Harvest
This is a question of efficiency comparisons between the ways to put elements into an array.
Take a look at the code:
Copy Code code as follows:

Way One
var arr = [];
var start = new Date ();
for (Var i=0;i<100000;i++) {
Arr.push (i);
}
Mode two
var arr = [];
var start = new Date ();
for (Var i=0;i<100000;i++) {
Arr[arr.length]=i;
}

Guess which is more efficient! After testing, the second approach is more efficient than the first.
Remind:
This version is incompatible with IE5, and here's what I'll explain:
1. When you get out of that thousand-point statistic, then go to the crazy money IE5 the clicks of the tester and the curiosity of the professional programmer for IE5, it is estimated that only the ashes of IE5 have been burned.
2. You want to believe that the use of Ashes to zero
3. If you have not yet been able to convince you, then I would like to say that you are very professional! That's why, there are ie3,ie2,ie? Ff1,nn4 ..., I think you should realize it together.
Some confessions: I'm not convincing myself, alas, to give a IE5 solution:
IE5 does not support the form of getelementbytagname ("*"), so here's the deal:
var elements = (tagname=== ' * ' &&node.all)? Node.all:node.getElementsByTagName (TagName);
Well, not much to say, this function is simple and practical, I also wrote a note on the code, see that there should be no problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.