Home > Web Front-end > JS Tutorial > 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?

Mary-Kate Olsen
Release: 2024-11-30 16:08:14
Original
608 people have browsed it

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>
Copy after login

You can access its class list by:

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

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 < classList.length; i++) {
    if (classList[i] === 'dolor_spec') {
        // Do something
    }
}
Copy after login

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!

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