Home >Web Front-end >JS Tutorial >How to Get an Element\'s Class List with jQuery?
jQuery provides comprehensive functions for manipulating elements in HTML documents. One common requirement is to access and process the class attributes of elements. This article addresses how to loop through or assign all the classes of an element to an array using jQuery.
The simplest approach to retrieve the class list of an element is through the className property. This property returns a string containing all the classes assigned to the element, separated by spaces. To convert this string into an array, you can use the following code:
var classList = document.getElementById('divId').className.split(/\s+/);
With the classList array, you can now iterate through each class and perform necessary actions.
jQuery provides the attr() function to access and manipulate attributes of elements, including the class attribute. To retrieve the class list as an array, you can use the following code:
var classList = $('#divId').attr('class').split(/\s+/); $.each(classList, function(index, item) { // Process each class });
This approach uses jQuery's $.each() function to iterate through the array of classes.
In cases where you only need to check for the presence of a specific class, jQuery's hasClass() function can be used:
if ($('#divId').hasClass('someClass')) { // Perform actions if element has 'someClass' }
This approach is efficient for checking for specific classes without the need to create an array.
The above is the detailed content of How to Get an Element\'s Class List with jQuery?. For more information, please follow other related articles on the PHP Chinese website!