Retrieving Element Class Names with jQuery
When working with HTML elements, it's often necessary to manage their class attributes. jQuery provides a range of methods for manipulating classes, but sometimes the task requires iterating through or retrieving all class names assigned to a specific element.
To achieve this, there are two primary ways:
Using JavaScript's native className Property:
var classList = document.getElementById('divId').className.split(/\s+/);
This method returns an array containing all the class names assigned to the element with the specified ID ('divId' in this case).
Using jQuery's attr() Method:
var classList = $('#divId').attr('class').split(/\s+/);
Similar to the native JavaScript approach, this method also returns an array of class names.
Note:
$.each(classList, function(index, item) { if (item === 'someClass') { //do something } });
The above is the detailed content of How Can I Retrieve All Class Names of an HTML Element Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!