Get elements by class name with javascript

// May 14th, 2009 // CSS, Javascript

Javascript does not support getting elements by class name; it only allows you to get elements by id. It is very useful having the ability to do this however, such as opening windows on a click when an anchor has an “external” class attached to it. As I don’t use frameworks such as JQuery for everything, I created this function which gets each element with a given class name and returns an array of each element.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
document.getElementsByClassName = function(className)
{
  var children = document.getElementsByTagName('*') || document.all;
  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;
}

4 Responses to “Get elements by class name with javascript”

  1. Jim says:

    But how do i use this on my site. Du i have to rename some of it’s content?

  2. admin says:

    I’m not sure what you mean. Basically this is DOM scripting, you want to get access to all elements with a class. One example is if you have set a class of “external” on links that you want to open a new window with. So you would call getElementsByClassName(‘external’) which would return an array of a elements that you could loop through and attach a function to. Hope that helps.

  3. admin says:

    What are you trying to achieve? What do you want to be able to do?

  4. Santosh Gada says:

    Thanks a lot. It’s working and it’s an cross browser solution.

Leave a Reply