Get class list for element with jQuery

Learn, how can we get a list of the classes that have been specified for an element using jQuery?
Submitted by Pratishtha Saxena, on September 07, 2022

Prerequisite: Adding jQuery to Your Web Pages

There can be multiple classes specified for a single element. An element can take up to all the characteristics of all the classes mentioned. These classes can be - custom CSS classes, predefined jQuery classes, bootstrap classes, etc. They can belong differently but the property of classes is the same globally. Therefore, we can treat them all just as some defined classes. Hence, sometimes it becomes necessary to know what all classes have been used for an HTML element.

By using the attr() method of jQuery, it is possible to know all the classes defined for an element. By declaring class as its parameter, it will return a list of classes defined for that element.

Syntax:

$("selector").attr("class");

Now, if we display this on the screen, it will display all the classes in one string without spaces. Hence, to make it presentable we'll be using regex (regular expression) to split the list. Once the list has been split, then we'll display the value of the array by traversing it with the help of the .each() loop of jQuery.

Syntax:

string.split(/\s+/);

Using this way, we can get the name of the classes that have been specified for an element.

Let's see the example given below.

Example to get class list for element with jQuery

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>Get Class List For An Element Using jQuery</h2>
    <p>Click the button to get the list of the classes used for the below div.</p>
    <br><br>
    <div class="Week Day Year Month Hour Second Minute" id="myDiv">- Monday is the First day of a week.</div>
    <br><br>
    <button type="button" id="button1">Get Class</button>
    <h3>Class List: </h3>
  </body>
  
<script type="text/javascript">
$(document).ready(function() {
    $('#button1').on('click', function() {
        var classes = $("#myDiv").attr("class");
        var list = classes.split(/\s+/);

        $.each(list, function(index, value) {
            $("h3").append(value + ' | ');
        });
    });
});
</script>
</html>

Output:

Example: Get class list for element





All jQuery Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.