jQuery attr() get class list from element

Description

jQuery attr() get class list from element

View in separate window

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Class List for Element</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        // Get class list string
        var classList = $("#myDiv").attr("class");

        // Creating class array by splitting class list string
        var classArr = classList.split(/\s+/);

        $.each(classArr, function(index, value){
            $("body").append("<p>" + index + ": " + value + "</p>");
        });/*from   w  w w.  j av  a2  s . c  o m*/
    });
});
</script>
</head>
<body>
    <div id="myDiv" class="foo bar bazz">
        <p>This is a paragraph inside DIV element</p>
    </div>
    <button type="button">Get Div Class List</button>
</body>
</html>



PreviousNext

Related