Get class list for element with jQuery

2018-12-31 05:37发布

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.

<div class="Lorem ipsum dolor_spec sit amet">Hello World!</div>

I will be looking for a "special" class as in "dolor_spec" above. I know that I could use hasClass() but the actual class name may not necessarily be known at the time.

17条回答
听够珍惜
2楼-- · 2018-12-31 06:09
var classList = $(element).attr('class').split(/\s+/);
$(classList).each(function(index){

     //do something

});
查看更多
宁负流年不负卿
3楼-- · 2018-12-31 06:09

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");}
    }
    });
} 
查看更多
墨雨无痕
4楼-- · 2018-12-31 06:12

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..

查看更多
零度萤火
5楼-- · 2018-12-31 06:13

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'));
查看更多
听够珍惜
6楼-- · 2018-12-31 06:14

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/

查看更多
登录 后发表回答