A encapsulated getElementsByClassName method is recommended

  • 2020-03-30 04:28:17
  • OfStack

As we know, native JS provides us with the getElementsByClassName method, which allows us to get a collection of nodes that contain a specified class, notice the collection, that is, this function returns an array.


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

Usage:


//First: select
for all div elements with box_box class under the document   getElementsByClassName(document,'box_box','div')[0].style.background='yellow'; //Second: select
for all div elements under the document with class box-box
  getElementsByClassName(document,'box-box','div')[0].style.background='yellow'; //Third: select all classes under the document to be box-box elements
  getElementsByClassName(document,'box-box')[0].style.background='yellow';

OEle, sClass is required, sEle is optional.

In sClass, there is no problem to test the horizontal line or underline, for example: box-box box_box; But other special characters are more likely to cause problems, such as box$box...   Of course, you can escape special characters by yourself, such as: box\\$box...

Compatibility: pro - test ie6+


Related articles: