Using jQuery to get the class list of elements

Posted by bashaash on Mon, 30 Dec 2019 17:56:50 +0100

Is there a way in jQuery to loop or assign all classes assigned to elements to arrays?

for example

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

I'll look for "special" classes in the "Dolor spec" above. I know I can use hasClass (), but the actual class name may not be known at that time.

#1 building

Why no one simply lists.

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

Edit: as @ mark Amery points out, you can't just. split(') because class names can be separated by any type of space.

#2 building

var classList = $(element).attr('class').split(/\s+/);
$(classList).each(function(index){

     //do something

});

#3 building

This is a jQuery plug-in that will return an array of all classes that the matching element has

;!(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 like this

$('div').classes();

As far as you are concerned

["Lorem", "ipsum", "dolor_spec", "sit", "amet"]

You can also pass functions to methods to be called on each class

$('div').classes(
    function(c) {
        // do something with each class
    }
);

This is the jsFiddle I set up for demonstration and testing http://jsfiddle.net/GD8Qn/8/

Streamline 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);

#4 building

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

Then, you can iterate and find the one you need.

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

jQuery doesn't really help you

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

#5 building

$('div').attr('class').split(' ').map(function(cls){ console.log(cls);})

Topics: JQuery Javascript