Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

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="Sample text 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.

1 Answer

0 votes
by (40.7k points)

You can try using document.getElementById('divId').className.split(/\s+/); to get an array of class names. Then you can iterate and find the one you want like this:

var classList = document.getElementById('divId').className.split(/\s+/);

for (var i = 0; i < classList.length; i++) {

    if (classList[i] === 'someClass') {

        //do something

    }

}

But jQuery will not be helpful here.

var classList = $('#divId').attr('class').split(/\s+/);

$.each(classList, function(index, item) {

    if (item === 'someClass') {

        //do something

    }

});

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...