Note that there are some explanatory texts on larger screens.

plurals
  1. POjavascript document.getElementsByClassName compatibility with IE
    text
    copied!<h3>What is the best method to retrieve an array of elements that have a certain class?</h3> <p>I would use document.getElementsByClassName but IE does not support it.</p> <p>So I tried <a href="http://snook.ca/archives/javascript/your_favourite_1" rel="nofollow noreferrer">Jonathan Snook's solution</a>:</p> <pre><code>function getElementsByClassName(node, classname) { var a = []; var re = new RegExp('(^| )'+classname+'( |$)'); var els = node.getElementsByTagName("*"); for(var i=0,j=els.length; i&lt;j; i++) if(re.test(els[i].className))a.push(els[i]); return a; } var tabs = document.getElementsByClassName(document.body,'tab'); </code></pre> <p>...but IE still says:</p> <blockquote> <p>Object doesn't support this property or method</p> </blockquote> <p>Any ideas, better methods, bug fixes?</p> <p>I would prefer not to use any solutions involving jQuery or other "bulky javascript".</p> <h1>Update:</h1> <p>I got it to work!</p> <p>As <a href="https://stackoverflow.com/a/7410966/552067">@joe mentioned</a> the function is not a method of <code>document</code>.</p> <p>So the working code would look like this:</p> <pre><code>function getElementsByClassName(node, classname) { var a = []; var re = new RegExp('(^| )'+classname+'( |$)'); var els = node.getElementsByTagName("*"); for(var i=0,j=els.length; i&lt;j; i++) if(re.test(els[i].className))a.push(els[i]); return a; } var tabs = getElementsByClassName(document.body,'tab'); </code></pre> <p><br> ...Also <strong>if you only need IE8+ support</strong> then this will work:</p> <pre><code>if(!document.getElementsByClassName) { document.getElementsByClassName = function(className) { return this.querySelectorAll("." + className); }; Element.prototype.getElementsByClassName = document.getElementsByClassName; } </code></pre> <p>Use it just like normal:</p> <pre><code>var tabs = document.getElementsByClassName('tab'); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload