Get class list for element with jQuery

后端 未结 17 1836
粉色の甜心
粉色の甜心 2020-11-22 03:20

Is there a way in jQuery to loop through or assign to an array all of the classes that are assigned to an element?

ex.

17条回答
  •  执笔经年
    2020-11-22 03:24

    Here is a jQuery plugin which will return an array of all the classes the matched element(s) have

    ;!(function ($) {
        $.fn.classes = function (callback) {
            var classes = [];
            $.each(this, function (i, v) {
                var splitClassName = v.className.split(/\s+/);
                for (var j = 0; j < splitClassName.length; j++) {
                    var className = splitClassName[j];
                    if (-1 === classes.indexOf(className)) {
                        classes.push(className);
                    }
                }
            });
            if ('function' === typeof callback) {
                for (var i in classes) {
                    callback(classes[i]);
                }
            }
            return classes;
        };
    })(jQuery);
    

    Use it like

    $('div').classes();
    

    In your case returns

    ["Lorem", "ipsum", "dolor_spec", "sit", "amet"]
    

    You can also pass a function to the method to be called on each class

    $('div').classes(
        function(c) {
            // do something with each class
        }
    );
    

    Here is a jsFiddle I set up to demonstrate and test http://jsfiddle.net/GD8Qn/8/

    Minified Javascript

    ;!function(e){e.fn.classes=function(t){var n=[];e.each(this,function(e,t){var r=t.className.split(/\s+/);for(var i in r){var s=r[i];if(-1===n.indexOf(s)){n.push(s)}}});if("function"===typeof t){for(var r in n){t(n[r])}}return n}}(jQuery);
    

提交回复
热议问题