javascript document.getElementsByClassName compatibility with IE

前端 未结 7 568
逝去的感伤
逝去的感伤 2020-11-22 08:44

What is the best method to retrieve an array of elements that have a certain class?

I would use document.getElementsByClassName but IE does not support it.

相关标签:
7条回答
  • 2020-11-22 09:32

    You can't really replicate getElementsByClassName, because it returns a nodeList, and so its value is live, and updates with the document.

    You can return a static Array of elements who share the same classnames- but it won't 'know'when the document changes.

    (It won't take too many of these kind of things to make a library look svelte...)

    function getArrayByClassNames(classes, pa){
        if(!pa) pa= document;
        var C= [], G;
        if(pa.getElementsByClassName){
            G= pa.getElementsByClassName(classes);
            for(var i= 0, L= G.length; i<L; i++){
                C[i]= G[i];
            }
        }
        else{
            classes= classes.split(/\s+/);
            var who, cL= classes.length,
            cn, G= pa.getElementsByTagName('*'), L= G.length;
            for(var i= 0; i<cL; i++){
                classes[i]= RegExp('\\b'+classes[i]+'\\b');
            }
            classnameLoop:
            while(L){
                who= G[--L];
                cn= who.className;
                if(cn){
                    for(var i= 0; i<cL; i++){
                        if(classes[i].test(cn)== false) {
                            continue classnameLoop;
                        }
                    }
                    C.push(who);
                }
            }
        }
        return C;
    }
    

    //Example

    var A= getArrayByClassNames('sideBar local')

    0 讨论(0)
提交回复
热议问题