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

Is there a betterfaster way to find all elements with a class name in browsers that don't support

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;
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745207732a4616673.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信