Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
156
rated 0 times [  161] [ 5]  / answers: 1 / hits: 8910  / 10 Years ago, thu, june 19, 2014, 12:00:00

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>

More From » jquery

 Answers
8

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)


[#44462] Wednesday, June 18, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
magaly

Total Points: 524
Total Questions: 96
Total Answers: 89

Location: India
Member since Wed, Aug 26, 2020
4 Years ago
;