JavaScript – How to use getElementsByClassName in IE8 or below

The getElementsByClassName is not available in IE8 or below. Therefore, if we use it, we will get the following error:

Object doesn't support property or method 'getElementsByClassName'

We can get the same error result if we use it in an IE Compatibility View mode with document mode is IE8 or lower too.

So to solve this, we need to implement a custom getElementsByClassName as shown below.

 

1. Implementation

Create a js file and define the following function.

dom-helper.js
function getElementsByClassName(clsName) {
    // if getElementsByClassName is available, use it
    if (document.getElementsByClassName) {
        return document.getElementsByClassName(clsName);
    }

    // if not, we try to find the elements having the
    // expected class name in all tags in the page
    var retnode = [];
    var element = document.getElementsByTagName('*');
    for (var i = 0; i < element.length; i++) {
        if ((' ' + element[i].className + ' ').indexOf(' ' + clsName + ' ') > -1) {
            retnode.push(element[i]);
        }
    }
    return retnode;
}; 

 

2. Usage and Example

Create a test HTML file and add the below code. Click on the “Run Example” button to see how it works.

test.htmlRun Example
<!DOCTYPE html>
<html>
<head>
    <title>JavaScript - How to use getElementsByClassName in IE8 or below | ByteNota</title>
</head>
<body>
    <p class="message">Lorem Ipsum is simply dummy text...</p>
    <p class="message">It has survived not only five centuries...</p>

    <div>
        <h3>Results:</h3>
        <p>Length: <span id="result-length"></span></p>
        <p>Content 1: <span id="result-content-1"></span></p>
        <p>Content 2: <span id="result-content-2"></span></p>

    </div>


    <script type="text/javascript">

        function getElementsByClassName(clsName) {
            // if getElementsByClassName is available, use it
            if (document.getElementsByClassName) {
                return document.getElementsByClassName(clsName);
            }

            // if not, we try to find the elements having the
            // expected class name in all tags in the page
            var retnode = [];
            var element = document.getElementsByTagName('*');
            for (var i = 0; i < element.length; i++) {
                if ((' ' + element[i].className + ' ').indexOf(' ' + clsName + ' ') > -1) {
                    retnode.push(element[i]);
                }
            }
            return retnode;
        }; 

        var messages = getElementsByClassName('message');

        document.getElementById('result-length').innerHTML = messages.length;
        document.getElementById('result-content-1').innerHTML = messages[0].innerText;
        document.getElementById('result-content-2').innerHTML = messages[1].innerText;
        console.log(messages);

    </script>

</body>
</html>