Ruby's Louvre

每天学习一点点算法

导航

getElementsByClassName

function getElementsByClassName(classname) {
  var elements;
  var pattern;
  var i;
  var results = [];

  if (doc.querySelectorAll) { // IE8
    return doc.querySelectorAll('.' + classname);
  }

  if (doc.evaluate) { // IE6, IE7
    pattern = './/*[contains(concat(" ", @class, " "), " " + classname + " ")]';
    elements = doc.evaluate(pattern, d, null, 0, null);
    while ((i = elements.iterateNext())) {
      results.push(i);
    }
  } else {
    elements = doc.getElementsByTagName('*');
    pattern = new RegExp('(^|\\s)' + classname + '(\\s|$)');
    for (var i = 0, length = elements.length; i < length; i++) {
      if (pattern.test(elements[i].className)) {
        results.push(elements[i]);
      }
    }
  }

  return results;
}

posted on 2017-02-09 14:21  司徒正美  阅读(1121)  评论(1编辑  收藏  举报