Get class list for element with jQuery

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

    Why has no one simply listed.

    $(element).attr("class").split(/\s+/);
    

    EDIT: Split on /\s+/ instead of ' ' to fix @MarkAmery's objection. (Thanks @YashaOlatoto.)

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

    Here you go, just tweaked readsquare's answer to return an array of all classes:

    function classList(elem){
       var classList = elem.attr('class').split(/\s+/);
        var classes = new Array(classList.length);
        $.each( classList, function(index, item){
            classes[index] = item;
        });
    
        return classes;
    }
    

    Pass a jQuery element to the function, so that a sample call will be:

    var myClasses = classList($('#myElement'));
    
    0 讨论(0)
  • 2020-11-22 03:45

    Might this can help you too. I have used this function to get classes of childern element..

    function getClickClicked(){
        var clickedElement=null;
        var classes = null;<--- this is array
        ELEMENT.on("click",function(e){//<-- where element can div,p span, or any id also a class
            clickedElement = $(e.target);
            classes = clickedElement.attr("class").split(" ");
            for(var i = 0; i<classes.length;i++){
                console.log(classes[i]);
            }
            e.preventDefault();
        });
    }
    

    In your case you want doler_ipsum class u can do like this now calsses[2];.

    0 讨论(0)
  • 2020-11-22 03:47
    $('div').attr('class').split(' ').each(function(cls){ console.log(cls);})
    
    0 讨论(0)
  • 2020-11-22 03:48

    Update:

    As @Ryan Leonard pointed out correctly, my answer doesn't really fix the point I made my self... You need to both trim and remove double spaces with (for example) string.replace(/ +/g, " ").. Or you could split the el.className and then remove empty values with (for example) arr.filter(Boolean).

    const classes = element.className.split(' ').filter(Boolean);
    

    or more modern

    const classes = element.classList;
    

    Old:

    With all the given answers, you should never forget to user .trim() (or $.trim())

    Because classes gets added and removed, it can happen that there are multiple spaces between class string.. e.g. 'class1 class2       class3'..

    This would turn into ['class1', 'class2','','','', 'class3']..

    When you use trim, all multiple spaces get removed..

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