-1

I have this code for document.getElementsByClassName for IE

if (!document.getElementsByClassName) { // 4ie

    document.getElementsByClassName = 
    function(classname) {
        var elArray = [],
            tmp = document.getElementsByTagName("*");
            regex = new RegExp("(^|\\s)" + classname + "(\\s|$)");
        for ( var i = 0; i < tmp.length; i++ ) {

            if ( regex.test(tmp[i].className) ) {
                elArray.push(tmp[i]);
            }
        }

        return elArray;
    };
}

How to change this code to make it work for single HTML element? Like div.getElementsByClassName('123')

James Montagne
  • 77,516
  • 14
  • 110
  • 130
user2950593
  • 9,233
  • 15
  • 67
  • 131

1 Answers1

1

You have a couple options. The first is that since getElementsByClassName always returns an array, if you know that based on the class name you passed it that it's only going to grab one element you can do getElementsByClassName('123')[0] to get that one element. If it grabs multiple elements then getElementsByClassName('123')[0] will return the first one.

Second you could add an Id which has to be unique to the singular element and use the getElementById() function to grab it.

Working Title
  • 254
  • 7
  • 28