Currently, this solution can be used to determine that the browser does not support this method. If this method is supported, the getElementsByClassName method will be added to the document object, if you are interested, you can understand that this method can be used to determine that browser support does not support this method. If this method is not supported, add the getElementsByClassName Method to the document Object, this method has the advantage that you do not need to modify the code whether or not there are native functions.
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
The 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 Var child = children [I];
Var classNames = child. className. split ('');
For (var j = 0; j If (classNames [j] = className ){
Elements. push (child );
Break;
}
}
}
Return elements;
};
}
The final solution is:
The Code is as follows:
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 Match = patterns [k]. test (current. className );
If (! Match) break;
}
If (match) result. push (current );
}
Return result;
}
}