Get class list for element with jQuery

后端 未结 17 1828
粉色の甜心
粉色の甜心 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: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]+"
    {

    }
    " } } } else { if (currentHtml.indexOf(class_name) <0) { currentHtml += "."+class_name+"
    {

    }
    " } } } else { console.log("none"); } }); $("#Test").html(currentHtml);

    });

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

提交回复
热议问题