Picture

Hi, I'm Boopathi Rajaa.

Hacker, Dancer, Biker, Adventurist

getElementsByClass - Javascript

One thing that is missing in javascript that is required most of the times is to get reference to Objects by its class name. Everytime we want it in usage, we had to write code related to the program that will get the reference to the Object using tag name, or id, and cross checking its class name with the function hasClass(). Now it is made simpler and in a generalised way.

Here is a function that will return all objects' reference as an array provided the arguments - [class name, the place/ branch/ node to search in, add the tag filter]. The second and third arguments are optional. Those are used only in cases where duplication is hard to distinguish.

function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}

Paste the above code in your script.js of your webpage or in your script tag and use it.

Note:

  • This is not a method defined to Object class. So you cannot use it as

    • var myClass = document.getElementsByClass("className");
  • It should be used in one of the following ways:

    • var myClass = getElementsByClass("className",document);
    • var myClass = getElementsByClass("className");
  • Also to be noted that it returns NOT a single element. It returns an array of elements. So even if there is only one class and you get the reference to that using this method, you should access it by myClass[0].

If any doubts regarding this, post your comments. Any imporvements to the script is also accepted. Do use this script. Found it very useful when creating animations using javascript.

Alternate Option:
If you are a developer and you are in a learning stage, it is recommended that you use a function above or create your own function. If you just want some method that would get you work done and you don't worry about how it is done, then the other easier way would be using jQuery. Download the latest jQuery library, and just call $("className"). This ll return the jQuery object where you can apply the methods defined under jQuery library.

Try Web Development. Its fun being a developer.