Get All Elements in an HTML document with a specific CSS Class

前端 未结 10 776
时光取名叫无心
时光取名叫无心 2020-12-01 04:10

What\'s the best way to get an array of all elements in an html document with a specific CSS class using javascript?

No javascript frameworks like jQuery allowed her

相关标签:
10条回答
  • 2020-12-01 05:00

    1) Get all elements in the document (document.getElementsByTagName('*'))
    2) Do a regular expression match on the element's className attribute for each element

    0 讨论(0)
  • 2020-12-01 05:07

    There is no such thing as a CSS class. CSS has rule-sets and selectors (including the class selector).

    Do you mean an HTML class? The usual way is to loop over every element in the document (using document.getElementsByTagName('*') (for efficiency, use a specific tag name if you know the class will only be applied to elements of a certain type) and test the className property of each (noting that the property contains a space separated list of class names, not a single class name).

    A number of libraries (such as jQuery or YUI) have functions to simply this.

    Do you mean a CSS selector? This gets more complex, and turning to a library is almost certainly the right thing to do here. Again, jQuery or YUI are decent choices.

    0 讨论(0)
  • 2020-12-01 05:08

    If using a framework, they all have selections using CSS Selectors. Otherwise.

    var getElementsByClassName = function(cls, sc){
        //Init
        var elements, i, results = [], curClass;  
    
        //Default scope is document
        sc = sc || document;
    
        //Get all children of the scope node
        elements = sc.getElementsByTagName('*');
        for( i=0; i < elements.length; i++ ){
            curClass = elements[i].getAttribute('class');
            if(curClass != null){
                curClass = curClass.split(" ");
                for( j=0; j < curClass.length; j++){
                    if(curClass[j] === cls){
                        results.push( elements[i] );
                        break;
                    }
                }
            }
        }
    
        return results;
    };
    

    Just wrote it right now, just for you. :) Feel free to use.

    0 讨论(0)
  • 2020-12-01 05:10

    You can include a getElementsByClass function, or you can use a jQuery selector.

    UPDATE: The implementation mentioned by @Shog9 is probably better than that above.

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