How to Get Element By Class in JavaScript?

This code should work in all browsers.

function replaceContentInContainer(matchClass, content) {
    var elems = document.getElementsByTagName('*'), i;
    for (i in elems) {
        if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ')
                > -1) {
            elems[i].innerHTML = content;
        }
    }
}

The way it works is by looping through all of the elements in the document, and searching their class list for matchClass. If a match is found, the contents is replaced.

jsFiddle Example, using Vanilla JS (i.e. no framework)

Leave a Comment