Home > Article > Web Front-end > Solution to the problem that IE browser does not support getElementsByClassName_javascript skills
The getElementsByClassName method has been added to DOM3, but it is not supported by other versions except IE9 and 10. This is a pain!
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.
Some people on the Internet directly define a getElementsByClassName function, but in this case, all uses of document.getElementsByClassName in the code need to be rewritten into getElementsByClassName. It's somewhat inconvenient and not universal.
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; 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; }; }