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
Release: 2024-11-30 18:09:12
Original
805 people have browsed it

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:

1

var classList = document.getElementById('divId').className.split(/\s+/);

Copy after login

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:

1

2

3

4

var classList = $('#divId').attr('class').split(/\s+/);

$.each(classList, function(index, item) {

    // Process each class

});

Copy after login

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:

1

2

3

if ($('#divId').hasClass('someClass')) {

    // Perform actions if element has 'someClass'

}

Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template