How to get element by class name?

Alpha picture Alpha · Jul 31, 2013 · Viewed 460.9k times · Source

Using JavaScript, we can get element by id using following syntax:

var x=document.getElementById("by_id");

I tried following to get element by class:

var y=document.getElementByClass("by_class");

But it resulted into error:

getElementByClass is not function

How can I get an element by its class?

Answer

Elias Van Ootegem picture Elias Van Ootegem · Jul 31, 2013

The name of the DOM function is actually getElementsByClassName, not getElementByClassName, simply because more than one element on the page can have the same class, hence: Elements.

The return value of this will be a NodeList instance, or a superset of the NodeList (FF, for instance returns an instance of HTMLCollection). At any rate: the return value is an array-like object:

var y = document.getElementsByClassName('foo');
var aNode = y[0];

If, for some reason you need the return object as an array, you can do that easily, because of its magic length property:

var arrFromList = Array.prototype.slice.call(y);
//or as per AntonB's comment:
var arrFromList = [].slice.call(y);

As yckart suggested querySelector('.foo') and querySelectorAll('.foo') would be preferable, though, as they are, indeed, better supported (93.99% vs 87.24%), according to caniuse.com: