Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate through classes on same element

If I have a div which has multiple classes assigned to the class attribute, is it possible to iterate through them using the each() function in jQuery?

<div class="class1 differentclassname anotherclassname"><div>
like image 746
Curtis Crewe Avatar asked Nov 30 '22 19:11

Curtis Crewe


2 Answers

In JavaScript, to get the list of classes, you can use

  • .className.split(' '), returns an Array
  • (HTML5) .classList, returns a DOMTokenList

In jQuery, you can use .prop() to get className or classList properties.

To iterate them, you can use:

  • A for loop, e.g. for(var i=0; i<classes.length; ++i)
  • (ES6) A for...of loop, e.g. for(var cl of classes).
  • (ES5) forEach, only for arrays, e.g. classes.forEach(fn)
  • (jQuery) $.each, e.g. $.each(classes, fn)

If you use classList but want to iterate using forEach, you can convert the DOMTokenList into an Array using

  • [].slice.call(classes)
  • (ES6) Array.from(classes)
like image 191
Oriol Avatar answered Dec 04 '22 09:12

Oriol


First you need to get an string that contains the classes with:

$('div').attr('class');

and split it with blank spaces to get an array with:

$('div).attr('class').split(' ');

and then use that array as the first argument to an $.each function where the index and the value can help you to handle it independently

$.each($('div').attr('class').split(' '), function(index, value) {
    console.log('Class name ' + value);
});
like image 31
Roberto Aguilar Avatar answered Dec 04 '22 09:12

Roberto Aguilar