The current solution is to determine whether the browser supports this method. If it supports it, leave it alone. If it does not support it, add the getElementsByClassName method to the document object. This way of writing has the advantage that you don’t have to go there regardless of whether there is a native function or not. Modify the code.
Usually use getElementsByTagName("*") to retrieve all elements in the document, then traverse, use regular expressions to find matching elements, put them into an array and return them. Since IE5 does not support document.getElementsByTagName("*"), use the branch document.all to prevent errors
The following method perfectly supports document writing
if (!document.getElementsByClassName){
document.getElementsByClassName = function(className, element){
var children = (element || document).getElementsByTagName('*');
var elements = new Array( );
for (var i=0; ivar child = children[i];
var classNames = child.className.split(' ');
for (var j=0; jif (classNames[j] == className){
elements.push(child);
break;
}
}
}
return elements;
};
}
The final solution is:
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; kmatch = patterns[k].test(current.className);
if (!match) break;
}
if (match) result.push(current);
}
return result;
}
}
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn