最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Better way to find all elements with a class name - Stack Overflow

programmeradmin1浏览0评论

Is there a better/faster way to find all elements with a class name in browsers that don't support document.getElementsByClassName?

var elements = document.getElementsByTagName('*'),
    results = [];

for (var i=0; i < elements.length; i++) {
  (elements[i].className === selector) ? results.push(elements[i]) : null;
}
return results;

And no I don't want to use jQuery :)

Is there a better/faster way to find all elements with a class name in browsers that don't support document.getElementsByClassName?

var elements = document.getElementsByTagName('*'),
    results = [];

for (var i=0; i < elements.length; i++) {
  (elements[i].className === selector) ? results.push(elements[i]) : null;
}
return results;

And no I don't want to use jQuery :)

Share Improve this question asked Nov 2, 2010 at 1:56 errorhandlererrorhandler 1,7673 gold badges22 silver badges29 bronze badges 6
  • 4 This doesn't actually get all the elements with the class, it gets the elements with only this class. – Nick Craver Commented Nov 2, 2010 at 1:58
  • Hey! I never noticed that :) is there a way to find elements with the class? – errorhandler Commented Nov 2, 2010 at 1:59
  • 1 @user494211 - Something like this: for (var i=0; i < elements.length; i++) { if (" "+elements[i].className+" ".indexOf(" "+selector+" ") !== -1) results.push(elements[i]); } – Nick Craver Commented Nov 2, 2010 at 2:05
  • @NickCraver: borrowing jQuery's hasClass method, are we? – OozeMeister Commented Aug 20, 2013 at 15:56
  • 1 @OozeMeister that approach has been around for as long as I can remember, and well before jQuery...the jQuery implementation is actually quite different. – Nick Craver Commented Aug 20, 2013 at 16:03
 |  Show 1 more ment

2 Answers 2

Reset to default 6

I would check out John Resig's parison on methods for simulating document.getElementsByClassName.

While IE8 doesn't support document.getElementsByClassName, it does support document.querySelectorAll, so that would be an option for IE8 anyway.

You could do something like:

function byClass( sel ) {
    var results;
    if( document.querySelectorAll ) {
        results = document.querySelectorAll( '.' + sel );
    } else if( document.getElementsByClassName ) {
        results = document.getElementsByClassName( sel );
    } else {
        var elements = document.getElementsByTagName('*'),
        results = [];
        // and so on
    }
    return results;
}
发布评论

评论列表(0)

  1. 暂无评论