Get class list for element with jQuery

后端 未结 17 1608
粉色の甜心
粉色の甜心 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:38

    A bit late, but using the extend() function lets you call "hasClass()" on any element, e.g.:
    var hasClass = $('#divId').hasClass('someClass');

    (function($) {
    $.extend({
        hasClass: new function(className) {
            var classAttr = $J(this).attr('class');
            if (classAttr != null && classAttr != undefined) {
                var classList = classAttr.split(/\s+/);
                for(var ix = 0, len = classList.length;ix < len;ix++) {
                    if (className === classList[ix]) {
                        return true;
                    }
                }
            }
            return false;
        }
    }); })(jQuery);
    

提交回复
热议问题