mozilla
Your Search Results

    Element.getElementsByClassName()

    The Element.getElementsByClassName() method returns a live HTMLCollection containing all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node.

    Similarly the method Document.getElementsByClassName() acts on the whole document; it will return elements which are descendants of the specified document root element with the given class names.

    Syntax

    var elements = element.getElementsByClassName(names);
    • elements is a live HTMLCollection of found elements.
    • names is a string representing the list of class names to match; class names are separated by whitespace
    • element is any Element of a document.

    Examples

    Get all elements that have a class of test:

    element.getElementsByClassName('test');

    Get all elements that have both the red and test classes:

    element.getElementsByClassName('red test');

    Get all elements that have a class of test, inside of an element that has the id of main:

    document.getElementById('main').getElementsByClassName('test');

    We can also use methods of Array.prototype on any HTMLCollection by passing the HTMLCollection as the method's this value. Here we'll find all <div> elements that have a class of test:

    var testElements = document.getElementsByClassName('test');
    var testDivs = Array.prototype.filter.call(testElements, function(testElement){
        return testElement.nodeName === 'div';
    });

    Specifications

    Specification Status Comment
    DOM
    The definition of 'Element.getElementsByClassName()' in that specification.
    Living Standard Initial definition

    Browser compatibility

    Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
    Basic support (Yes) (Yes) [1] (Yes) (Yes) (Yes)
    Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
    Basic support ? ? [1] ? ? ?

    [1] Prior to Firefox 19, this method was returning a NodeList; it was then changed to reflects the change in the spec.

    Document Tags and Contributors

    Contributors to this page: Sheppy, fscholz, fredy, nairakhil13, bergus, Brettz9, kscarfone, teoli
    Last updated by: bergus,
    Hide Sidebar