Click here to Skip to main content
15,893,594 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
In my page i have different tags and different classes for tags now i need to get class names of all the elements using jquery ....is it possible?
Posted
Comments
Thanks7872 19-Mar-15 8:56am    
Not clear. Show the sample of code you have and point out the issue in the same.
Member 11355723 19-Mar-15 9:01am    
<html>
<head>


</style>
<script type="text/javascript">
function readClassName() {
var elem = document.getElementById('div1');
var elem1 = document.getElementById('div2');

alert(elem.className +" " +elem1.className); // Gets the class name

}
</script>

</head>
<body>
<p id="myp" class="pstyle1">Element content ...</p>
<div id="div1" class="div1cls"></div>
<div id="div2" class="div2cls"></div>
<button >Get and Set Class Name</button>
</body>
</html>


here i have two divisions and used javascript to find the class names of two div's when click on button by using element by id but now i need to use jquery

Try this:
C#
$('#div1').attr('class');//output : div1cls
$('#div2').attr('class');//output : div2cls

Regards..
 
Share this answer
 
Comments
Member 11355723 19-Mar-15 9:10am    
how can i display output in alert box ..i have used it but it is not displaying class names
Thanks7872 19-Mar-15 9:33am    
alert($('#div1').attr('class'));
Try this:
XML
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    // loop through all html elements
    $("*").each(function() {
        var element = $(this).prop('class');
        if (element != '') { // if the element has class name
            alert(element);
        }
    });
});
</script>
</head>
<body>
<p class="paragraph">A Paragraph</p>
<button class="button">A Button</button>
</body>
</html>

Read more:
1. All Selector (“*”)[^]
2. .each()[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900