"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Get and Manipulate an Element\'s Class List with jQuery?

How Can I Get and Manipulate an Element\'s Class List with jQuery?

Published on 2025-01-28
Browse:296

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:

Hello World!

You can access its class list by:

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

This results in an array of the following strings:

  • "Lorem"
  • "ipsum"
  • "dolor_spec"
  • "sit"
  • "amet"

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 

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3