This can be resolved so far, that the browser does not support this method, if the support does not matter, if not supported, in the Document object to add Getelementsbyclassname this method, such a writing has the advantage that no matter whether there is no native function you do not have to modify the code.
You typically use getElementsByTagName ("*") to remove all elements of a document, and then iterate through it, using regular expressions to find matching elements to return to an array. Because IE5 does not support document.getElementsByTagName ("*"), use branch document.all to prevent errors
The following method perfectly supports document writing.
Copy Code code 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 scenario is:
Copy Code code 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<kl; k++) {
Match = Patterns[k].test (current.classname);
if (!match) break;
}
if (match) Result.push (current);
}
return result;
}
}