Home > Web Front-end > JS Tutorial > How to Retrieve an Array of Element Classes with jQuery?

How to Retrieve an Array of Element Classes with jQuery?

Susan Sarandon
Release: 2024-11-27 08:17:13
Original
398 people have browsed it

How to Retrieve an Array of Element Classes with jQuery?

How to Get an Array of Element Classes with jQuery

Question: Can jQuery be used to obtain an array of classes assigned to an element, including a specific class (dolor_spec in the example)?

Example:

<div class="Lorem ipsum dolor_spec sit amet">Hello World!</div>
Copy after login

Limitations:

  • hasClass() is not suitable because the exact class name may be unknown at runtime.

Solution:

Using JavaScript (without jQuery):

const classList = document.getElementById('divId').className.split(/\s+/);
Copy after login

Iterate through the class list to find the desired class:

for (var i = 0; i < classList.length; i++) {
    if (classList[i] === 'dolor_spec') {
        // Do something
    }
}
Copy after login

Using jQuery:

jQuery does not offer a direct solution for this task. Here is an alternative approach:

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

Iterate through the class list with jQuery's each() function:

$.each(classList, function(index, item) {
    if (item === 'dolor_spec') {
        // Do something
    }
});
Copy after login

Checker Function:

if ($('#divId').hasClass('dolor_spec')) {
    // Do something
}
Copy after login

The above is the detailed content of How to Retrieve an Array of Element Classes 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