Home >Web Front-end >JS Tutorial >How Can I Get and Manipulate an Element\'s Class List with jQuery?
Get Class List for Element with jQuery
In jQuery, you can retrieve the class list of an element using the attr('class') method, which returns a string containing all the assigned classes. To obtain an array of these classes, you can split the string based on whitespaces using split(/s /);.
For example, if you have an element with the HTML:
<div class="Lorem ipsum dolor_spec sit amet">Hello World!</div>
You can access its class list by:
var classList = $('#divId').attr('class').split(/\s+/);
This results in an array of the following strings:
To find a specific class, such as "dolor_spec", you can iterate through the array and compare each element to your desired class name.
for (var i = 0; i < classList.length; i++) { if (classList[i] === 'dolor_spec') { // Do something } }
Although jQuery provides the hasClass() method to check if an element has a particular class, it requires the class name to be known beforehand. If the actual class name is variable, you can use the array-based approach to find and manipulate the desired class.
The above is the detailed content of How Can I Get and Manipulate an Element\'s Class List with jQuery?. For more information, please follow other related articles on the PHP Chinese website!