Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Benjamin Keller
20,763 PointsWhat method returns an array of all classes for an element?
The title contains most of it. I believe I remember using such a method in one lesson, but I can't remember which one. I believe it's a jquery method that allowed you to assign all the classes. it would look something like
var classList = $element.methodThatReturnsArrayOfClasses();
var cheese = classList[1];
<div class="ex cheese"></div>
1 Answer
Christopher Misa
6,467 PointsThere's a property of all elements in the DOM called 'classList' that returns an array of classes to which that element belongs. It's designed to let you add, remove, test, and toggle classes (as in: element.classList.add("class_name"); ), but you can also access classes directly as per your example (element.classList[0] being the first).
Also, you can use jquery's addClass() method to add a bunch of classes at once (as in $element.addClass("class1 class2 class3 class4"); ). However, it's a little tricky to use jquery to get an array of classes like the one found in the DOM (see: http://www.jqueryfaqs.com/Articles/Get-list-of-class-names-when-multiple-classes-using-jQuery.aspx).