SoFunction
Updated on 2025-03-10

Recommend a packaged getElementsByClassName method

We know that the native JS provides us with the getElementsByClassName method, which can obtain a collection of nodes containing a specified class through this method. Note that it is a collection, that is, this function returns an array.

However, IE does not support this method, but this method is very practical, so we have to implement such a function specifically for IE.

Copy the codeThe code is as follows:

function getElementsByClassName(oEle,sClass,sEle){
  if(){
    return (sClass);
  }else{
    var aEle=(sEle || '*'),
      reg=new RegExp('(^|\\s)'+sClass+'($|\\s)'),
      arr=[],
      i=0,
      iLen=;

    for(; i<iLen; i++){
      if((aEle[i].className)){
        (aEle[i]);
      }
    }
    return arr;
  }
}

How to use:

Copy the codeThe code is as follows:

//The first type: select all the class under the document as the div elements of box_box
  getElementsByClassName(document,'box_box','div')[0].='yellow';

//The second type: select all the class under the document as the div elements of box-box
  getElementsByClassName(document,'box-box','div')[0].='yellow';

//The third type: select all classes under the document as box-box elements
  getElementsByClassName(document,'box-box')[0].='yellow';

oEle and sClass are required, sEle is optional.

There is no problem with the horizontal line or underscore in sClass, such as box-box box_box; but if it is other special characters, it is very likely that there will be problems, such as box$box... Of course, you can add escapes to get special characters yourself, such as box\\$box...

Compatibility: Test ie6+

Friends, you will know it by using it yourself. It’s super easy to use. Let’s spread it to other friends.