Necessity, the mother of invention

  • Visitor Map

    Locations of Site Visitors
  • Flag Counter

    free counters

getElementByClassName in Javascript

Posted by Navi's on April 29, 2010

We already use document.getElementById and document.getElementByTagName but what if we have a html control that doesn’t have any id. It has only applied css class.
In that case we need to find out that control using applied class.

function getElementByClassName(sourceElement,ClassName){
var ctrl=sourceElement.childNodes;
for (var i = 0; i < ctrl.length; i++)
        if (ctrl[i].className == ClassName) {
                  //here we get that control and do what ever you want

This is the basic function with sourceElement and ClassName parameter. Here the sourceElement is the

element which contains that div or control you want to find i.e. parant element and the ClassName is the css class that applied on that div or control which you want to find.

This is helpful if you are not using any javascript library i.e. jQuery, prototype, dojo etc…


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: