Get class list for element with jQuery

后端 未结 17 1623
粉色の甜心
粉色の甜心 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);
    
    0 讨论(0)
  • 2020-11-22 03:25

    Thanks for this - I was having a similar issue, as I'm trying to programatically relate objects will hierarchical class names, even though those names might not necessarily be known to my script.

    In my script, I want an <a> tag to turn help text on/off by giving the <a> tag [some_class] plus the class of toggle, and then giving it's help text the class of [some_class]_toggle. This code is successfully finding the related elements using jQuery:

    $("a.toggle").toggle(function(){toggleHelp($(this), false);}, function(){toggleHelp($(this), true);});
    
    function toggleHelp(obj, mode){
        var classList = obj.attr('class').split(/\s+/);
        $.each( classList, function(index, item){
        if (item.indexOf("_toggle") > 0) {
           var targetClass = "." + item.replace("_toggle", "");
           if(mode===false){$(targetClass).removeClass("off");}
           else{$(targetClass).addClass("off");}
        }
        });
    } 
    
    0 讨论(0)
  • 2020-11-22 03:27

    On supporting browsers, you can use DOM elements' classList property.

    $(element)[0].classList
    

    It is an array-like object listing all of the classes the element has.

    If you need to support old browser versions that don't support the classList property, the linked MDN page also includes a shim for it - although even the shim won't work on Internet Explorer versions below IE 8.

    0 讨论(0)
  • 2020-11-22 03:31

    You can follow something like this.

    $('#elementID').prop('classList').add('yourClassName')
    $('#elementID').prop('classList').remove('yourClassName')
    
    0 讨论(0)
  • 2020-11-22 03:33

    Try This. This will get you the names of all the classes from all the elements of document.

    $(document).ready(function() {
    var currentHtml="";
    $('*').each(function() {
        if ($(this).hasClass('') === false) {
            var class_name = $(this).attr('class');
            if (class_name.match(/\s/g)){
                var newClasses= class_name.split(' ');
                for (var i = 0; i <= newClasses.length - 1; i++) {
                    if (currentHtml.indexOf(newClasses[i]) <0) {
                        currentHtml += "."+newClasses[i]+"<br>{<br><br>}<br>"
                    }
                }
            }
            else
            {
                if (currentHtml.indexOf(class_name) <0) {
                    currentHtml += "."+class_name+"<br>{<br><br>}<br>"
                }
            }
        }
        else
        {
            console.log("none");
        }
    });
    $("#Test").html(currentHtml);
    

    });

    Here is the working example: https://jsfiddle.net/raju_sumit/2xu1ujoy/3/

    0 讨论(0)
  • 2020-11-22 03:36
    var classList = $(element).attr('class').split(/\s+/);
    $(classList).each(function(index){
    
         //do something
    
    });
    
    0 讨论(0)
提交回复
热议问题