document.getElementsByClassName() 原生方法 通过className 选择DOM节点

时间:2023-11-26 12:16:02

<div id="box">
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box3">3</div>
</div>

function getElementsByClassName(node,className){

  if(node.getElementsByClassName){

    /*兼容ie9*/
    return node.getElementsByClassName(className);
  }else{
    var results = [];
    var items = node.getElementsByTagName("*");
    for (var i = 0; i < items.length; i++) {
      if(items[i].className == className){
        results.push(items[i]);
      }
    };
    return results;
  }
}
var node = document.getElementById('box');
console.log(getElementsByClassName(node,"box"));