document.getElementsByClassName

JavaScript polyfill, by , Wednesday, March 12th, 2014

Getting elements by class name is something we often need to do, but unfortunately not all browsers support the document.getElementsByClassName() method, so I have written a little polyfill to do the job, just in case;

  1. if (document.getElementsByClassName) {
  2. document.getElementsByClassName = function (className) {
  3. var result = [],
  4. body = document.body;
  5. // Traversing the DOM using a IIFE passing it
  6. // the body element and the sorting function
  7. (function traverseDOM (node, fn) {
  8. // We only check for a match, if we have
  9. // an ELEMENT_NODE.
  10. if (node.nodeType === 1) {
  11. fn(node, className);
  12. }
  13. node = node.firstChild;
  14. // While the current node still have child nodes
  15. // we iterate over them.
  16. while (node) {
  17. // We traverse any potential child nodes of this node.
  18. traverseDOM(node, fn);
  19. node = node.nextSibling;
  20. }
  21. }(body, function (elem, cName) {
  22. // If we have a match push it to the results array.
  23. // Some browsers do not support node.className,
  24. // hence the node.getAttribute('class')
  25. if ((' ' + (elem.className || elem.getAttribute('class')) + ' ').indexOf(' ' + cName + ' ') >= 0) {
  26. result.push(elem);
  27. }
  28. }));
  29. return result;
  30. };
  31. }

This example uses recursion, which I really like, but you can do it in many different ways. Here is another example, which essentially does the same, but instead of using recursion it simply iterates over all elements using a simple for-loop;

  1. if (document.getElementsByClassName) {
  2. document.getElementsByClassName = function (className) {
  3. var result = [],
  4. // Fetching all elements.
  5. elements = document.getElementsByTagName('*'),
  6. len = elements.length,
  7. i,
  8. node;
  9. for (i = 0; i < len; i += 1) {
  10. node = elements[i];
  11. if ((' ' + (node.className || node.getAttribute('class')) + ' ').indexOf(' ' + className + ' ') >= 0) {
  12. result.push(node);
  13. }
  14. }
  15. return result;
  16. };
  17. }