Javascript getElementsByClassName implementation code

Source: Internet
Author: User

Let's take a look at the Code: (Multiple class queries and queries within a certain range are supported)
Copy codeThe Code is as follows:
/*
* Obtain the Element Set Based on the element clsssName.
* @ Param fatherId the ID of the parent element. The default value is document.
* @ TagName the label name of the sub-element
* @ ClassName A className string 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 ++ ){
// Create a regular expression matching the 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 attribute
Var element = elements [I];
While (className [k ++]. test (element. className) {// optimized the loop
If (k = classNameLength ){
Result [result. length] = element;
Break;
}
}
K = 0;
}
Return result;
}

Okay. Let's test:
Copy codeThe Code is 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 codeThe Code is 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
}

The result is correct.
Native getElementsByClassName
Some people may ask, the native method call efficiency is the highest, and many browsers have already implemented the getElementsByClassName method. Why didn't we call the native method before calling the custom method?
Yes, the native efficiency is very high. It supports queries with multiple class conditions, but the biggest problem is that it does not support getElementsByClassName ("container", "div ", "aaa ccc"), which is used to find the specified element as the specified class in the specified tag.
Therefore, native method calls are discarded here.
Questions about cyclic Optimization
In the code, you will see that I have cached the length of the array to improve efficiency. In fact, there is a very hidden problem here, that is, the access length attribute of the array is very different from the access length attribute of the HtmlCollection. In an array, length is a common attribute and no additional operations are performed during access. To see HTMLCollection, we often use HTMLCollection as an array, but in fact, it is an object that automatically changes according to the DOM structure. Each time you access the attributes of an HTMLCollection object, it will perform a complete match on all the nodes in the DOM. That is to say, each time you access the length of the HtmlCollection object, the set object will be updated, which consumes a lot of performance. Therefore, we recommend that you cache the length of this HtmlCollection loop operation.
Additional gains
This is about the efficiency comparison between the ways to put elements into the array.
Let's take a look at the Code:
Copy codeThe Code is as follows:
// Method 1
Var arr = [];
Var start = new Date ();
For (var I = 0; I <100000; I ++ ){
Arr. push (I );
}
// Method 2
Var arr = [];
Var start = new Date ();
For (var I = 0; I <100000; I ++ ){
Arr [arr. length] = I;
}

Let's guess, which one is more efficient! After testing, the efficiency of the second method is higher than that of the first method.
Reminder:
This version is not compatible with IE5. The following is my explanation:
1. from the statistics of the thousands, the IE5 testers who are crazy about money click and the curiosity of professional programmers about IE5, it is estimated that only IE5 is burned to the ashes.
2. You want to believe that the use value of ashes tends to be zero.
3. If you haven't been able to convince you, I 'd like to say that you are very professional! Now, is there IE3, IE2, or IE? FF1, nn4..., I think you should implement it together.
Some frankness: I didn't quite convince myself. Alas, let's give an IE5 solution:
IE5 does not support the getElementByTagName ("*") format, so here we need to handle it:
Var elements = (tagName = '*' & node. all )? Node. all: node. getElementsByTagName (tagName );
Well, let's not talk about it much. This function is simple and practical. I also wrote comments on the code to understand 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.