Get class list for element with jQuery

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

    You can use document.getElementById('divId').className.split(/\s+/); to get you an array of class names.

    Then you can iterate and find the one you want.

    var classList = document.getElementById('divId').className.split(/\s+/);
    for (var i = 0; i < classList.length; i++) {
        if (classList[i] === 'someClass') {
            //do something
        }
    }
    

    jQuery does not really help you here...

    var classList = $('#divId').attr('class').split(/\s+/);
    $.each(classList, function(index, item) {
        if (item === 'someClass') {
            //do something
        }
    });
    

提交回复
热议问题