Home >Web Front-end >JS Tutorial >How to Get an Element\'s Class List with jQuery?

How to Get an Element\'s Class List with jQuery?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 18:09:12707browse

How to Get an Element's Class List with jQuery?

How to Retrieve Class List of an Element 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.

Using Element.className

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.

Using jQuery Attribute Function

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.

Using jQuery hasClass() Function

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn