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>
Limitations:
Solution:
Using JavaScript (without jQuery):
const classList = document.getElementById('divId').className.split(/\s+/);
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 } }
Using jQuery:
jQuery does not offer a direct solution for this task. Here is an alternative approach:
const classList = $('#divId').attr('class').split(/\s+/);
Iterate through the class list with jQuery's each() function:
$.each(classList, function(index, item) { if (item === 'dolor_spec') { // Do something } });
Checker Function:
if ($('#divId').hasClass('dolor_spec')) { // Do something }
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!