Currently, this solution can be used to determine that the browser does not support this method. If it does not support this method, add the getElementsByClassName Method to the document Object. This method has the following advantages, no matter whether there are native functions, you do not need to modify the code.
Generally, getElementsByTagName ("*") is used to retrieve all elements in the document, traverse them, and use regular expressions to find matching elements and put them in an array to return the results. Because IE5 does not support document. getElementsByTagName ("*"), use the branch document. all to prevent errors.
The following method perfectly supports document writing
Copy codeThe Code is as follows: if (! Document. getElementsByClassName ){
Document. getElementsByClassName = function (className, element ){
Var children = (element | document). getElementsByTagName ('*');
Var elements = new Array ();
For (var I = 0; I <children. length; I ++ ){
Var child = children [I];
Var classNames = child. className. split ('');
For (var j = 0; j <classNames. length; j ++ ){
If (classNames [j] = className ){
Elements. push (child );
Break;
}
}
}
Return elements;
};
}
The final solution is:Copy codeCode: var getElementsByClassName = function (searchClass, node, tag ){
If (document. getElementsByClassName ){
Var nodes = (node | document). getElementsByClassName (searchClass), result = [];
For (var I = 0; node = nodes [I ++];) {
If (tag! = "*" & Node. tagName = tag. toUpperCase ()){
Result. push (node)
} Else {
Result. push (node)
}
}
Return result
} Else {
Node = node | document;
Tag = tag | "*";
Var classes = searchClass. split (""),
Elements = (tag = "*" & node. all )? Node. all: node. getElementsByTagName (tag ),
Patterns = [],
Current,
Match;
Var I = classes. length;
While (-- I> = 0 ){
Patterns. push (new RegExp ("(^ | \ s)" + classes [I] + "(\ s | $ )"));
}
Var j = elements. length;
While (-- j> = 0 ){
Current = elements [j];
Match = false;
For (var k = 0, kl = patterns. length; k <kl; k ++ ){
Match = patterns [k]. test (current. className );
If (! Match) break;
}
If (match) result. push (current );
}
Return result;
}
}